Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Retrieving a List from a java.util.stream.Stream in Java 8

I was playing around with Java 8 lambdas to easily filter collections. But I did not find a concise way to retrieve the result as a new list within the same statement. Here is my most concise approach so far:

List<Long> sourceLongList = Arrays.asList(1L, 10L, 50L, 80L, 100L, 120L, 133L, 333L); List<Long> targetLongList = new ArrayList<>(); sourceLongList.stream().filter(l -> l > 100).forEach(targetLongList::add); 

Examples on the net did not answer my question because they stop without generating a new result list. There must be a more concise way. I would have expected, that the Stream class has methods as toList(), toSet(), …

Is there a way that the variables targetLongList can be directly be assigned by the third line?

like image 476
Daniel K. Avatar asked Feb 12 '13 10:02

Daniel K.


People also ask

Which method is used to convert stream to List?

This class has the toList() method, which converts the Stream to a List.

How do you collect data from a stream?

Gather all the stream's items in the collection created by the provided supplier. Count the number of items in the stream. Sum the values of an Integer property of the items in the stream. Calculate the average value of an Integer property of the items in the stream.

How do I get one element from a stream List?

Using Stream findFirst() Method: The findFirst() method will returns the first element of the stream or an empty if the stream is empty. Approach: Get the stream of elements in which the first element is to be returned. To get the first element, you can directly use the findFirst() method.

How can we get a stream from a List in Java?

Using List. stream() method: Java List interface provides stream() method which returns a sequential Stream with this collection as its source.


1 Answers

What you are doing may be the simplest way, provided your stream stays sequential—otherwise you will have to put a call to sequential() before forEach.

[later edit: the reason the call to sequential() is necessary is that the code as it stands (forEach(targetLongList::add)) would be racy if the stream was parallel. Even then, it will not achieve the effect intended, as forEach is explicitly nondeterministic—even in a sequential stream the order of element processing is not guaranteed. You would have to use forEachOrdered to ensure correct ordering. The intention of the Stream API designers is that you will use collector in this situation, as below.]

An alternative is

targetLongList = sourceLongList.stream()     .filter(l -> l > 100)     .collect(Collectors.toList()); 
like image 89
Maurice Naftalin Avatar answered Oct 02 '22 21:10

Maurice Naftalin