Sort Map by Value using Custom Comparator

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

Name class as key of HashMap
1
2
3
4
5
public class Name {
private String firstName;
private String lastName;
//builder
}
Name class as key of HashMap
1
2
3
4
5
6
  
public class Age {
private Integer year;
private Integer month;
//builder
}

We want to sort Map by Age.Year.

Sort map by value using Comparator
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
	
Map<Name, Age> 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();

Age age0 = Age.builder().year(30).month(5).build();
Age age1 = Age.builder().year(66).month(3).build();
Age age2 = Age.builder().year(17).month(6).build();
Age age3 = Age.builder().year(3).month(5).build();
Age age4 = Age.builder().year(50).month(5).build();
Age age5 = Age.builder().year(80).month(12).build();

map.put(name0,age0);
map.put(name1,age1);
map.put(name2,age2);
map.put(name3,age3);
map.put(name4,age4);
map.put(name5,age5);

Comparator<Age> byAge = (Age obj1,Age obj2) -> obj1.getYear().compareTo(obj2.getYear());

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

Source Code Github Link

Share Comments