Skip to content

Instantly share code, notes, and snippets.

@itzg
Created December 4, 2020 21:23
Show Gist options
  • Save itzg/667dbd322a4a19550f8e1ccd0f6ef938 to your computer and use it in GitHub Desktop.
Save itzg/667dbd322a4a19550f8e1ccd0f6ef938 to your computer and use it in GitHub Desktop.
Using Collectors.toMap with map supplier and mergeFunction
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.TreeMap;
import java.util.stream.Collectors;
class Scratch {
public static void main(String[] args) {
final TreeMap<Object, Object> results = List.of(
Map.entry("one", 1),
Map.entry("one", "I"),
Map.entry("one", "first"),
Map.entry("two", 2)
).stream()
.collect(Collectors.toMap(
Entry::getKey,
Entry::getValue,
(o, o2) -> {
System.out.printf("mergeFunction called with %s, %s%n", o, o2);
return o;
},
TreeMap::new
));
System.out.println(results);
}
}
@itzg
Copy link
Author

itzg commented Dec 4, 2020

Output:

mergeFunction called with 1, I
mergeFunction called with 1, first
{one=1, two=2}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment