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 :
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.