首页主机资讯Java怎么对hashmap的数据进行排序

Java怎么对hashmap的数据进行排序

时间2024-02-29 08:42:03发布访客分类主机资讯浏览1537
导读:Java中的HashMap是无序的数据结构,如果想要对HashMap中的数据进行排序,可以将其转换为List,然后对List进行排序。 下面是一个示例代码: import java.util.*; public class SortHas...

Java中的HashMap是无序的数据结构,如果想要对HashMap中的数据进行排序,可以将其转换为List,然后对List进行排序。

下面是一个示例代码:

import java.util.*;


public class SortHashMap {

    public static void main(String[] args) {
    
        HashMapString, Integer>
     hashMap = new HashMap>
    ();
    
        hashMap.put("Alice", 30);
    
        hashMap.put("Bob", 20);
    
        hashMap.put("Charlie", 25);
    
        
        ListMap.EntryString, Integer>
    >
     list = new ArrayList>
    (hashMap.entrySet());
    
        
        // 使用Comparator对List进行排序
        Collections.sort(list, new ComparatorMap.EntryString, Integer>
    >
() {
    
            @Override
            public int compare(Map.EntryString, Integer>
     o1, Map.EntryString, Integer>
 o2) {
    
                return o1.getValue().compareTo(o2.getValue());

            }

        }
    );
    
        
        // 打印排序后的结果
        for (Map.EntryString, Integer>
 entry : list) {
    
            System.out.println(entry.getKey() + " : " + entry.getValue());

        }

    }

}
    

在这个示例中,首先将HashMap转换为List,然后使用Comparator对List进行排序,最后打印排序后的结果。

声明:本文内容由网友自发贡献,本站不承担相应法律责任。对本内容有异议或投诉,请联系2913721942#qq.com核实处理,我们将尽快回复您,谢谢合作!


若转载请注明出处: Java怎么对hashmap的数据进行排序
本文地址: https://pptw.com/jishu/632639.html
mongodb怎么查询并统计数组内个数 c语言分解质因数问题怎么解决

游客 回复需填写必要信息