I recently learned about threads in Java 8 and started working with them. Now I have a question regarding the groupingBy
collector method:
I usually work with .NET, so I compared (knowing that they are not the same) Java Stream<T>
with .NET IEnumerable<T>
. After this comparison, List<T>
stores the elements, and specific Stream
/ IEnumerable
apply operations. One example:
FROM#:
elements.Where(x => x.Value == 5).ToList();
Java:
elements.stream().filter(x -> x.getValue() == 5).collect(Collectors.toList());
In both examples, I start with a list, define operations (filter in this example), and collect the result to save it (in a new list in this example).
Now I got a more complicated case:
data.stream() .map( ... ).filter( ... )
The result of this query is Map<String, Long>
, and I can work with it, but, say, I want to continue this data, and not store it. My current approach is trivial:
... .collect(groupingBy(Chunk::getName, summingLong(Chunk::getValue))) .entrySet().stream(). .map( ... )
But in this way I leave the stream, save the first result on the map and open a new stream to continue. Is there a way to group without a collector so that I can "stay" in the stream?
source share