Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create array of incremental int using Stream instead of for loop

I want to create a function that builds an array of incremental numbers.

For example, I want to obtain something like:

int[] array = new int[]{1, 2, 3, 4, 5, 6, 7, 8, ..., 1000000};

The function will receive two parameters: start number (inclusive) and the final length of the array:

public int[] buildIncrementalArray(int start, int length) { ... }

I know how to do it using a for loop:

public int[] buildIncrementalArray(int start, int length) {
    int[] result = new int[length];
    for(int i = 0 ; i < length ; i++) {
        result[i] = start + i;
    }
    return result;
}

Instead of using a for loop, I want to use Java 8 Stream API. Does anybody know how to do it using Stream API?

like image 274
jfcorugedo Avatar asked Sep 28 '15 12:09

jfcorugedo


People also ask

Which method in stream can be used to create an array from the stream?

The stream(T[] array) method of Arrays class in Java, is used to get a Sequential Stream from the array passed as the parameter with its elements. It returns a sequential Stream with the elements of the array, passed as parameter, as its source.

How do you create an array of streams in Java?

public static <T> Stream<T> getStream(T[] arr) { return Arrays. stream(arr); } where, T represents generic type. Example 1 : Arrays. stream() to convert string array to stream.


1 Answers

There is already a built-in method for that:

int[] array = IntStream.range(start, start + length).toArray();

IntStream.range returns a sequential ordered IntStream from the start (inclusive) to the end (exclusive) by an incremental step of 1.

If you want to include the end element, you can use IntStream.rangeClosed.

like image 165
Tunaki Avatar answered Nov 12 '22 12:11

Tunaki