Java 8: performing a stream reduction operation

I have java.util.stream.Stream containing key value pairs, for example:

<1,3> <1,5> <3,1> <4,2> <4,7> <4,8> 

Now I would like to combine all the records that have the same key:

 <1,[3,5]> <3,[1]> <4,[2,7,8]> 

Data has already been sorted, so only sequential data sets need to be combined.

Now I'm looking for a way to convert the contents of a stream, as described above, without loading all the data sets into memory.

I would rather get java.util.stream.Stream as a result with a different type of object containing a list of values โ€‹โ€‹instead of a single value.

My only approach is a custom iterator that does the merge, but seems pretty ugly to convert to an iterator and back to a stream.

What is the best approach for him?

+5
source share
1 answer

Here is the SteamEx solution.

 int[][] datasets = { { 1, 3 }, { 1, 5 }, { 3, 1 }, { 4, 2 }, { 4, 7 }, { 4, 8 } }; StreamEx.of(datasets) // .collapse((a, b) -> a[0] == b[0], groupingBy(a -> a[0], mapping(a -> a[1], toList()))) // .forEach(System.out::println); 

you can replace int[] with a dataset object. We can add peek to check without lazy loading / calculation:

 StreamEx.of(datasets) // .peek(System.out::println) // .collapse((a, b) -> a[0] == b[0], groupingBy(a -> a[0], mapping(a -> a[1], toList()))) // .limit(1) // .forEach(System.out::println); 
+4
source

Source: https://habr.com/ru/post/1268569/


All Articles