Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create a int[] or a Collection<Integer> with the value 0,1,2,...,N in one line in Java using lambda expression?

Tags:

java

lambda

I would like to do something like this:

int[] seq = new int[N];
for (int i = 0 ; i < N ; i++) {
    seq[i] = i;
}

...in one line, and i am wondering if it is possible with lambda expression.

If it works with ArrayList<Integer>, it is okay for me.

like image 687
Eliott Roynette Avatar asked Feb 08 '18 11:02

Eliott Roynette


People also ask

What does int [] do in Java?

Since int[] is a class, it can be used to declare variables. For example, int[] list; creates a variable named list of type int[].

What is use of Lambda expression in Java?

The Lambda expression is used to provide the implementation of an interface which has functional interface. It saves a lot of code. In case of lambda expression, we don't need to define the method again for providing the implementation.

What is the type of a Lambda expression in Java 8?

Lambda Expressions were added in Java 8. A lambda expression is a short block of code which takes in parameters and returns a value. Lambda expressions are similar to methods, but they do not need a name and they can be implemented right in the body of a method.


1 Answers

Starting from Java 9 you can use the three-argument IntStream.iterate:

int[] seq = IntStream.iterate(0, x -> x < N, x -> x + 1).toArray();

Where:

IntStream.iterate​(int seed, IntPredicate hasNext, IntUnaryOperator next):

  • seed - the initial element;
  • hasNext - a predicate to apply to elements to determine when the stream must terminate;
  • next - a function to be applied to the previous element to produce a new element.
like image 63
Oleksandr Pyrohov Avatar answered Oct 22 '22 20:10

Oleksandr Pyrohov