Nov
29
2015

Sorting list of maps based on a key, value pair values

In this post of java tutorial i will see how to Sort list of maps based on value of a single <key, sortingCriteriaValue> pair of maps. For example let we have student list of maps. Map have three key value pair having name, collage and course of students. We want to sort student list based on name of student.

List<Map<String, String>> student = new ArrayList<Map<String, String>>();

student.add(new HashMap<String, String>() {{
put(“name”, “devender kumar”);
put(“collage”, “PIET”);
put(“course”, “b.tech”);
}});

student.add(new HashMap<String, String>() {{
put(“name”, “ankush jain”);
put(“collage”, “ARYA”);
put(“course”, “M.tech”);
}});

student.add(new HashMap<String, String>() {{
put(“name”, “ankit jain”);
put(“collage”, “PSOM”);
put(“course”, “MBA”);
}});

 

For this we need to Implement your own Comparator<Map<Key, Value>> based on map.get(“name”). Let see the complete program

When we run this program then we will see sorted list of student based on their name.

before sorting [{course=b.tech, name=devender kumar, collage=PIET}, {course=M.tech, name=ankush jain, collage=ARYA}, {course=MBA, name=ankit jain, collage=PSOM}]
after sorting [{course=MBA, name=ankit jain, collage=PSOM}, {course=M.tech, name=ankush jain, collage=ARYA}, {course=b.tech, name=devender kumar, collage=PIET}]

This is all in this post. Hope this is helpful.

Comments are closed.