Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sorting HashMap

Tags:

java

I have an ArrayList of HashMap. Each HashMap contains many key-value-pairs. I want to sort the ArrayList by the value of the key distance in the 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);
}
like image 333
user687022 Avatar asked Dec 12 '22 09:12

user687022


2 Answers

Add all the HashMaps to a list and sort it using a custom Comparator like this:

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);
}
like image 131
dacwe Avatar answered Jan 04 '23 03:01

dacwe


You can try to sort with a custom 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 all your values are strings which is not the case in your example (distance is an int value).

like image 22
Howard Avatar answered Jan 04 '23 04:01

Howard