How to Sort Java HashMap Data

In Java, HashMap is an unordered data structure. If you want to sort the data in HashMap, you can convert it to a List and then sort the List.

Here is a sample code:

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

In this example, the HashMap is first converted into a List, which is then sorted using a Comparator, and finally the sorted result is printed.

bannerAds