Collect Stream Elements Into a List in Java
Collecting Stream Elements Into a List In Java
Java developers often need to collect elements from a Stream and store them in a List. Fortunately, this process is straightforward with the help of a few utility methods. This article will explain how to perform this task in a few steps.
Using Collectors.toList() to Collect Stream Elements
The Collectors.toList() method is part of the Collectors class in Java 8, and it allows you to convert a Stream into a List. It takes a single argument: The Collector object that specifies how the elements should be added to the list.
For example, if you wanted to create a List of the numbers from 0 to 9, you could do so using the following snippet of code:
List<Integer> numbers = IntStream.range(0, 10) .boxed() .collect(Collectors.toList());
In this case, the boxed() method is used to convert the Stream of ints into a Stream of Integers. Then the collect() method is used to collect the elements of the Stream and store them in the List.
Using Stream.collect() To Collect Stream Elements
You can also use the collect() method on a Stream directly instead of calling Collectors.toList(). It takes two arguments: an initial value for the accumulator and a BiFunction that is used to add elements to the accumulator. For example, the following code creates a List of the numbers from 0 to 9:
List<Integer> numbers = IntStream.range(0, 10) .boxed() .collect(ArrayList::new, ArrayList::add, ArrayList::addAll);
In this case, the collect() method is given three arguments: an initial value of a new ArrayList, a BiFunction that adds an element to the list, and a BiFunction that adds all the elements of one list to another.
Conclusion
Collecting elements from a Stream and storing them in a List is a common task for Java developers. Fortunately, there are several ways to accomplish this, such as the Collectors.toList() method and the Stream.collect() method. With either of these methods, you can easily convert a Stream into a List, making your code more efficient and readable.