How to create an array of numbers from (1 to x)?

Running on JDK 16. Originally tried to figure out how to create an array of numbers like range(1,x+1) in python.

Tried to use the built in help in VSC to no avail, then switched to IntelliJ and that made me even more confused without the intellisense of VSC. Searched google for two hours straight trying stuff like instream and then converting to an array, but failed. Tried type-casting to int[] but that didn’t work either. Haven’t been able to figure it out even with the smart sense of W3Schools and searching here for an hour..

The problem: I want to create an array of numbers from 1 to x. Let’s say x is equal to 25. Then, i’d like to iterate through them one by one in a for loop. Inside the four loop, I want to cube it by three and build a dynamic array that has ‘x’ slots. (So, 25 in this instance.)

Here’s what i’ve tried so far:

import java.util.Scanner;
import java.util.stream.Collectors;
import java.util.stream.IntStream;

public class cubeNums {
    public static void someVoidMethod() {
        Scanner scan = new Scanner(System.in);
        System.out.println("Please enter x: ");
        // take in x val
        int x = scan.nextInt();
        // create int[] array to iterate thru for loop
        list numList = (IntStream.range(-2, 10)).boxed().collect(Collectors.toList());


        for (int[] numArray = new int[15]) {
              //incomplete
        }


    }

}

This is just the latest attempt I have of the code, after re-writing it a bunch and having no luck..

Answer

You can create range from x to y, using stream range, then you can replace generated values with map and put these values to an array using toArray

public static void main(String[] args) {
    int[] arr = IntStream.range(1, 25).map(x -> (int) Math.pow(x, 3)).toArray();
    System.out.println(Arrays.toString(arr));
}

If you want to get a list, you first need to box the numbers with boxed and call collect

List<Integer> list = IntStream
        .range(1, 25)
        .map(x -> (int) Math.pow(x, 3))
        .boxed()
        .collect(Collectors.toList());

System.out.println(list);

Output

[1, 8, 27, 64, 125, 216, 343, 512, 729, 1000, 1331, 1728, 2197, 2744, 3375, 4096, 4913, 5832, 6859, 8000, 9261, 10648, 12167, 13824]