HashMap Sort

I have an ArrayList of HashMap . Each HashMap contains many key-value pairs. I want to sort an ArrayList by the value of the distance key in a HashMap .

 ArrayList<HashMap<String, String>> arrayListHashMap = new ArrayList<HashMap<String, String>>(); { HashMap hashMap = new HashMap<String, Object>(); hashMap.put("key", "A key"); hashMap.put("value", "B value"); hashMap.put("distance", 2536); arrayListHashMap.add(hashMap); } { HashMap hashMap = new HashMap<String, String>(); hashMap.put("key", "B key"); hashMap.put("value", "A value"); hashMap.put("distance", 2539); arrayListHashMap.add(hashMap); } 
+4
source share
2 answers

You can try sorting using a specialized comparator:

 Collections.sort(arrayListHashMap, new Comparator<HashMap<String, String>>() { @Override public int compare(HashMap<String, String> m1, HashMap<String, String> m2) { return Integer.valueOf(m1.get("distance")).compareTo(Integer.valueOf(m2.get("distance"))); } }); 

Note that I assumed that all of your values ​​are strings that don't match your example (distance is an int value).

+6
source

Add all the HashMap to the list and sort it using a custom Comparator as follows:

 Collections.sort(arrayListHashMap, new Comparator<HashMap<String, Object>>() { @Override public int compare(HashMap<String, Object> o1, HashMap<String, Object> o2) { return ((Integer) o1.get("distance")).compareTo( (Integer) o2.get("distance")); } }); 

Full example:

 public static void main(String... args) { List<HashMap<String, Object>> arrayListHashMap = new ArrayList<HashMap<String, Object>>(); { HashMap<String, Object> hashMap = new HashMap<String, Object>(); hashMap.put("key", "A key"); hashMap.put("value", "B value"); hashMap.put("distance", 2536); arrayListHashMap.add(hashMap); } { HashMap<String, Object> hashMap = new HashMap<String, Object>(); hashMap.put("key", "B key"); hashMap.put("value", "A value"); hashMap.put("distance", 2539); arrayListHashMap.add(hashMap); } Collections.sort(arrayListHashMap, new Comparator<HashMap<String, Object>>() { @Override public int compare( HashMap<String, Object> o1, HashMap<String, Object> o2) { return ((Integer) o1.get("distance")).compareTo( (Integer) o2.get("distance")); } }); System.out.println(arrayListHashMap); } 
+8
source

Source: https://habr.com/ru/post/1369444/


All Articles