Reputation: 321
I would like to find a one-liner expression in Java that allows to instantiate an ArrayList
and to insert some specific elements inside it.
For example, an expression that creates an ArrayList
containing the numbers in the interval [0, n]
divisible by 3.
I manage to insert the filtered elements into the ArrayList
, but only using the forEach
expression in the following way:
ArrayList<Integer> numberList = new ArrayList<Integer>;
IntStream.range(0, n + 1)
.filter(number -> number % 3 == 0)
.forEach(number -> numberList.add(number));
As you can see, it's necessary to separately instantiate the ArrayList
and then insert the elements.
In Python, we can use the following one-liner:
numberList = [number for number in range(0, n + 1) if number % 3 == 0]
Is there something equivalent or similar to the code below in Java 8?
Thanks in advance.
Upvotes: 3
Views: 247
Reputation: 2397
You can use a collector to add the elements in a list :
int n = 10;
List<Integer> list = IntStream.range(0, n + 1)
.filter(number -> number % 3 == 0)
.boxed() // converts IntStream to Stream<Integer> (primitive type to wrapper type)
.collect(Collectors.toList());
Edit: As Aominè said in the comments, you can also use IntStream.rangeClosed(0, n)
instead of IntStream.range(0, n + 1)
Upvotes: 6