Sort HashMap in Java: Full Guide

In Java, HashMap is an unordered data structure. If you need to sort the key-value pairs in a HashMap, you can achieve this using the following method:

  1. Convert the key-value pairs in a HashMap to a List, and then sort the List.
HashMap<String, Integer> map = new HashMap<>();
// 添加键值对到map
List<Map.Entry<String, Integer>> list = new ArrayList<>(map.entrySet());
Collections.sort(list, new Comparator<Map.Entry<String, Integer>>() {
    public int compare(Map.Entry<String, Integer> o1, Map.Entry<String, Integer> o2) {
        return o1.getValue().compareTo(o2.getValue());
    }
});
  1. By using a TreeMap, you can take advantage of its ordered Map data structure, which allows sorting by key or value.
HashMap<String, Integer> map = new HashMap<>();
// 添加键值对到map
TreeMap<String, Integer> sortedMap = new TreeMap<>(new Comparator<String>() {
    public int compare(String o1, String o2) {
        return map.get(o1).compareTo(map.get(o2));
    }
});
sortedMap.putAll(map);
bannerAds