Created
December 4, 2020 21:23
-
-
Save itzg/667dbd322a4a19550f8e1ccd0f6ef938 to your computer and use it in GitHub Desktop.
Using Collectors.toMap with map supplier and mergeFunction
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Output: