Sort Map by key using Custom Comparator

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

We want to sort below Map by FirstName. Name object is used as key for Map.

Name class as key of HashMap
1
2
3
4
5
public class Name {
private String firstName;
private String lastName;
//builder
}
Sort map by Key using Comparator
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
	
Map<Name, Integer> map = new HashMap<>();
Name name0 = Name.builder().firstName("Zendor").lastName("Sonawane").build();
Name name1 = Name.builder().firstName("Niraj").lastName("Sonawane").build();
Name name2 = Name.builder().firstName("Pratik").lastName("Sonawane").build();
Name name3 = Name.builder().firstName("Jeetesh").lastName("Sonawane").build();
Name name4 = Name.builder().firstName("Rahul").lastName("Sonawane").build();
Name name5 = Name.builder().firstName("Amit").lastName("Sonawane").build();
map.put(name0,55);
map.put(name1,1);
map.put(name2,2);
map.put(name3,3);
map.put(name4,4);
map.put(name5,5);

This is how we can do that

Sort map by Key using Comparator
1
2
3
4
5
6

Comparator<Name> byName = (Name o1, Name o2)-> o1.getFirstName().compareTo(o2.getFirstName());

LinkedHashMap<Name, Integer> sortedMap = map.entrySet().stream()
.sorted(Map.Entry.<Name,Integer>comparingByKey(byName))
.collect(Collectors.toMap(Map.Entry::getKey,Map.Entry::getValue,(e1,e2)->e1,LinkedHashMap::new));

Source Code Github Link

Share Comments