Is there a non-terminal version of groupingBy
or some other neat way to stream through the resulting Map entries/values?
I find myself wanting to stream through the values after groupingBy
but the best I could come up with is not pretty:
StreamEx.ofValues(
StreamEx.of(0, 1, 2, 4).groupingBy(i -> i % 2)
).mapToInt(ii -> IntStreamEx.of(ii).sum())
// RESULT: [6, 1]
Doing this in a single Stream pipeline would probably require the wanted operation to act like a full barrier: in order to group the values, we need to process them all to see which values are even and odd (and be able to sum them).
As such, it is probably preferable to use a temporary data structure to hold the count of even and odd values, which in this case would be a
Map<Integer, Integer>
or even aMap<Boolean, Integer>
(where, for example, the key would betrue
for even values andfalse
for odd values, usingCollectors.partitioningBy
).Note that you don't need to use the StreamEx library here. You can do this directly the Stream API: