amaembo / streamex

Enhancing Java Stream API
Apache License 2.0
2.18k stars 249 forks source link

method collapseKeys on unsorted EntryStream #276

Closed wangguofeng1923 closed 6 months ago

wangguofeng1923 commented 6 months ago

Map<String,List> map1= EntryStream.of("1", 1,"2",4, "1", 2).sortedBy(Entry::getKey).collapseKeys().toMap();//works fine System.out.println(map1); // {1=[1, 2], 2=[4]}

//Duplicate entry for key '1' (attempt to merge values '[1]' and '[2]') Map<String,List> map2= EntryStream.of("1", 1,"2",4, "1", 2).collapseKeys().toMap(); System.out.println(map2);

not sure this is feature or bug. thx

amaembo commented 6 months ago

Yes, it's expected. As [javadoc](https://www.javadoc.io/doc/one.util/streamex/latest/one.util.streamex/one/util/streamex/EntryStream.html#collapseKeys()) says, collapse "Merge series of adjacent stream entries with equal keys".

The easiest way to solve your problem is to use grouping():

Map<String, List<Integer>> map = 
            EntryStream.of("1", 1, "2", 4, "1", 2).grouping();