繁体   English   中英

对HashMap进行排序

[英]Sorting HashMap

我有一个HashMapArrayList 每个HashMap包含许多键值对。 我想通过HashMapdistance的值对ArrayList进行排序。

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);
}

将所有HashMap添加到列表中并使用自定义Comparator对其进行排序,如下所示:

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"));
    }
});

完整示例:

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);
}

您可以尝试使用自定义比较器进行排序:

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")));
    }
});

请注意,我假设您的所有值都是字符串,而您的示例中并非如此(distance是一个int值)。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM