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.
List?