溫馨提示×

Java怎么對hashmap的數據進行排序

小億
106
2024-02-19 11:56:22
欄目: 編程語言

Java中的HashMap是無序的數據結構,如果想要對HashMap中的數據進行排序,可以將其轉換為List,然后對List進行排序。

下面是一個示例代碼:

import java.util.*;

public class SortHashMap {
    public static void main(String[] args) {
        HashMap<String, Integer> hashMap = new HashMap<>();
        hashMap.put("Alice", 30);
        hashMap.put("Bob", 20);
        hashMap.put("Charlie", 25);
        
        List<Map.Entry<String, Integer>> list = new ArrayList<>(hashMap.entrySet());
        
        // 使用Comparator對List進行排序
        Collections.sort(list, new Comparator<Map.Entry<String, Integer>>() {
            @Override
            public int compare(Map.Entry<String, Integer> o1, Map.Entry<String, Integer> o2) {
                return o1.getValue().compareTo(o2.getValue());
            }
        });
        
        // 打印排序后的結果
        for (Map.Entry<String, Integer> entry : list) {
            System.out.println(entry.getKey() + " : " + entry.getValue());
        }
    }
}

在這個示例中,首先將HashMap轉換為List,然后使用Comparator對List進行排序,最后打印排序后的結果。

0
亚洲午夜精品一区二区_中文无码日韩欧免_久久香蕉精品视频_欧美主播一区二区三区美女