Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Sort data by keys on the map

I want to sort my data based on the ID key in the below code. Is there a solution?

List<Map<String, Object>> baseList = new ArrayList<>();
for (int i = 1; i <= 5; i++) {
    Map<String, Object> map = new HashMap<>();
    map.put("ID", i);
    map.put("Name", "aa");
    baseList.add(map);
}
System.out.println(baseList);

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

In your sample code, the list is already sorted by ID, but if that is just sample input:

Since you want to sort the list, your can just use the sort method and specifiy that the ID in the map is supposed to be the sort key:

baseList.sort(Comparator.comparing(m -> (Integer)m.get("ID")));

Since that Map returns Object, you have to cast the value behind "ID" to Integer since Object itself does not implement Comparable.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading