I recently learned about streams in Java 8 and started to work with them. Now I have a question regarding the groupingBy
collector method:
Usually I work with .NET, so I compared (knowing they are not the same) Java Stream<T>
with .NET IEnumerable<T>
. Following this comparison, List<T>
stores elements and the particular Stream
/IEnumerable
applies operations. One example:
C#:
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 (a filter in this example) and collect the result to store it (in a new list in this example).
Now I got a more complex case:
data.stream()
.map( ... ).filter( ... ) // Some operations
.collect(groupingBy(Chunk::getName, summingLong(Chunk::getValue)));
The result of this query is a Map<String, Long>
and I can work with this, but lets say, I want to proceed with this data instead of storing it. My current approach is trivial:
...
.collect(groupingBy(Chunk::getName, summingLong(Chunk::getValue)))
.entrySet().stream().
.map( ... ) // Do more operations
But this way, I leave the stream, store the first result in a 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?