Java Stream - Sort map by key

Photo by Anton Lecock on Unsplash




In this Article , we’ll Discuss How we can Sort map by key in java 8.

We want to sort below Map by key
Sort map by Key
1
2
3
4
5
6
7
Map<String, Integer> map = new HashMap<>();
map.put("Niraj", 6);
map.put("Rahul", 43);
map.put("Ram", 44);
map.put("Sham", 33);
map.put("Pratik", 5);
map.put("Ashok", 5);

Map Sorting using comparingByKey in Ascending order

Sort map by Key Ascending order
1
2
3
4
Map<String, Integer> sortedMapByValueAscending 
= map.entrySet()
.stream().sorted(Map.Entry.comparingByKey())
.collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue, (e1, e2) -> e1,LinkedHashMap::new));

Map Sorting using comparingByKey in Descending order. For Descending order you need to use reversed()

Sort map by Key Descending order
1
2
3
4
Map<String, Integer> sortedMapByValueDescending
= map.entrySet()
.stream().sorted(Map.Entry.<String,Integer>comparingByKey().reversed())
.collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue, (e1, e2) -> e1 ,LinkedHashMap::new));

Source Code Github Link

Share Comments