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.
Since int[] is a class, it can be used to declare variables. For example, int[] list; creates a variable named list of type int[].
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.
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.
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.If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With