温馨提示×

hashmap怎么排序

小亿
102
2024-01-14 03:21:07
栏目: 编程语言

HashMap是一个无序的集合,它不支持排序。但是可以根据HashMap的键或值进行排序。

  1. 根据键排序:

    • 将HashMap的键集合转换为List,并使用Collections.sort()方法对List进行排序。
    HashMap<String, Integer> map = new HashMap<>();
    // 添加键值对到map
    List<String> sortedKeys = new ArrayList<>(map.keySet());
    Collections.sort(sortedKeys);
    // 遍历排序后的键集合并访问对应的值
    for (String key : sortedKeys) {
        Integer value = map.get(key);
        System.out.println(key + ": " + value);
    }
    
  2. 根据值排序:

    • 将HashMap的键值对转换为List,并使用Collections.sort()方法对List进行排序,根据值的大小进行排序。
    HashMap<String, Integer> map = new HashMap<>();
    // 添加键值对到map
    List<Map.Entry<String, Integer>> sortedEntries = new ArrayList<>(map.entrySet());
    Collections.sort(sortedEntries, (entry1, entry2) -> entry1.getValue().compareTo(entry2.getValue()));
    // 遍历排序后的键值对并访问键和值
    for (Map.Entry<String, Integer> entry : sortedEntries) {
        String key = entry.getKey();
        Integer value = entry.getValue();
        System.out.println(key + ": " + value);
    }
    

注意:以上排序方法只能对键或值是基本类型的HashMap进行排序。如果HashMap的键或值是自定义对象,需要自定义比较器(comparator)来实现排序。

0