3

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.

1
  • What about collecting to a List? Commented Jan 30, 2018 at 13:44

1 Answer 1

6

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)

Sign up to request clarification or add additional context in comments.

4 Comments

Thank you, this is perfect. I tried to use the collect() method without using boxed() before. With boxed() everything works fine
@AlessandroBardini In this case you would have to do .collect(ArrayList::new, List::add, List::addAll); which would be the equivalent of .boxed().collect(toCollection(ArrayList::new));
Both should have the same performance. The former (with boxed) is neater.
more suitable to use IntStream.rangeClosed(0, n) rather than IntStream.range(0, n + 1) in this case.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.