hashmap

hashmap遍历是否可以自定义排序

小樊
87
2024-07-11 18:53:30
栏目: 编程语言

在Java中,HashMap是无序的,因此无法对HashMap的遍历进行自定义排序。如果想要按照特定的顺序进行遍历,可以考虑将HashMap中的键值对放入一个List中,然后对List进行排序,最后再遍历排序后的List。以下是一个示例代码:

import java.util.*;

public class SortHashMap {

    public static void main(String[] args) {
        Map<String, Integer> hashMap = new HashMap<>();
        hashMap.put("Alice", 25);
        hashMap.put("Bob", 30);
        hashMap.put("Charlie", 20);
        hashMap.put("David", 35);

        List<Map.Entry<String, Integer>> list = new ArrayList<>(hashMap.entrySet());
        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.getKey().compareTo(o2.getKey());
            }
        });

        for (Map.Entry<String, Integer> entry : list) {
            System.out.println(entry.getKey() + ": " + entry.getValue());
        }
    }
}

在上面的代码中,我们先将HashMap中的键值对放入一个List中,然后通过Collections.sort()方法对List进行排序,最后再遍历排序后的List。在Comparator的compare方法中,我们可以自定义排序的逻辑。

0
看了该问题的人还看了