Sorting a Map Based on Values
To sort the Map based on values, we need to create a List from Map.entrySet()
. This method returns all the key-value pairs from the Map. Comparator function comes into play when sorting a particular set depends on multiple parameters. In the comparator function, return student1.getValue().compareTo(student2.getValue());
decides the way of sorting, i.e., by value, and this will sort the Map based on values.
List<Map.Entry<String, Integer>> studentList = new ArrayList<>(students.entrySet());
Collections.sort(studentList, new Comparator<Map.Entry<String, Integer>>() {
@Override
public int compare(Map.Entry<String, Integer> student1, Map.Entry<String, Integer> student2) {
return student1.getValue().compareTo(student2.getValue());
}
});