溫馨提示×

Java怎么對hashmap的數(shù)據(jù)進(jìn)行排序

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

Java中的HashMap是無序的數(shù)據(jù)結(jié)構(gòu),如果想要對HashMap中的數(shù)據(jù)進(jìn)行排序,可以將其轉(zhuǎn)換為List,然后對List進(jìn)行排序。

下面是一個(gè)示例代碼:

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進(jìn)行排序
        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());
            }
        });
        
        // 打印排序后的結(jié)果
        for (Map.Entry<String, Integer> entry : list) {
            System.out.println(entry.getKey() + " : " + entry.getValue());
        }
    }
}

在這個(gè)示例中,首先將HashMap轉(zhuǎn)換為List,然后使用Comparator對List進(jìn)行排序,最后打印排序后的結(jié)果。

0