How To Use Stream Sorted For Map

How To Use Stream Sorted For Map

這篇介紹How To Use Stream Sorted For Map.

Solution

1
2
3
4
5
6
7
8
9
10
11
12
13
Map<String, String> cache = new HashMap<>();
cache.put("1","1");
cache.put("3","3");
cache.put("2","2");

Map<String, String> sortedMap = cache.entrySet().stream().sorted(Map.Entry.comparingByKey())
.collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue,
(oldValue, newValue) -> oldValue, LinkedHashMap::new));

sortedMap - Output:
("1","1")
("2","2")
("3","3")