📌  相关文章
📜  根据值对 Hashmap 进行排序(1)

📅  最后修改于: 2023-12-03 15:26:41.696000             🧑  作者: Mango

根据值对 Hashmap 进行排序

在Java中,可以使用Hashmap来存储键值对。但是,如果需要根据值对Hashmap进行排序,应该如何实现呢?

以下是一种实现方式:

首先将Hashmap中的键值对存储到一个List中:

// 创建一个HashMap
HashMap<String, Integer> map = new HashMap<String, Integer>();

// 添加元素
map.put("apple", 10);
map.put("orange", 5);
map.put("banana", 20);

// 将HashMap转换为List
List<Map.Entry<String, Integer>> list = new ArrayList<Map.Entry<String, Integer>>(map.entrySet());

接着,可以使用Collections类中的sort方法来对List进行排序。在排序时,可以为sort方法传递一个实现了Comparator接口的比较器对象。

// 对List进行排序
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());
    }
});

以上代码中的比较器对象用来比较两个Map.Entry对象的值,根据值的大小来进行排序。如果希望按照键进行排序,可以将o1.getValue().compareTo(o2.getValue())替换为o1.getKey().compareTo(o2.getKey())。

最后,在排序后的List中遍历元素即可:

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

完整代码如下:

import java.util.*;

public class SortHashMapByValue {

    public static void main(String[] args) {

        // 创建一个HashMap
        HashMap<String, Integer> map = new HashMap<String, Integer>();

        // 添加元素
        map.put("apple", 10);
        map.put("orange", 5);
        map.put("banana", 20);

        // 将HashMap转换为List
        List<Map.Entry<String, Integer>> list = new ArrayList<Map.Entry<String, Integer>>(map.entrySet());

        // 对List进行排序
        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());
            }
        });

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

    }

}

以上代码将输出:

orange 5
apple 10
banana 20

总结:

以上是一种实现方式,可根据具体情况选择其他实现方式,如通过实现Comparable接口来对HashMap进行排序。无论哪种方式,都可以通过将HashMap转换为List,并使用Collections.sort方法来对List进行排序来实现。