之前对Java的Map按值排序很迷惑,一直想通过重写Comparator来实现但没有成功,最终参考网上,用流操作实现了按值排序,但是这个疙瘩一直纠结不去,按道理来说是可以通过重写Comparator实现任何自定义排序的,最近又自己尝试了一下,终于是实现了(虽然相对于流操作显得很臃肿),代码如下
import priorityQueueTest.PriorityQueueTest;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
/**
* @author mazheng
* @title: Solution
* @projectName workDemo
* @description: TODO 一个简单的测试类
* @date 2021/1/10 16:26
*/
public class SimpleTestSolution {
public static void main(String[] args) {
// 这里拿PriorityQueue举例,因为我之前做的操作就是取Map中最小值,但是要保留它的key信息,这里实现用了Map.Entry
PriorityQueue<Map.Entry<String, Integer>> priorityQueue = new PriorityQueue<>(new Comparator<Map.Entry<String, Integer>>() {
@Override
public int compare(Map.Entry<String, Integer> o1, Map.Entry<String, Integer> o2) {
return o1.getValue() - o2.getValue();
}
});
// 定义Map,并塞进去几个值
Map<String, Integer> map = new HashMap<>();
map.put("11", 1);
map.put("33", 3);
map.put("22", 2);
map.put("55", 5);
map.put("44", 4);
// 这一行需要注意一下
priorityQueue.addAll(map.entrySet());
// 打印一下结果
while (!priorityQueue.isEmpty()) {
System.out.println(priorityQueue.poll());
}
}
}
结果
符合预期。
因为PriorityQueue数据类型用的Map.Entry,所以如果操作不是打印,而是其他计算操作的话,要用Map.Entry的getKey()和getValue()方法,这也是我为什么说这样实现比较臃肿啰嗦的原因。可以的话还是要用Stream流实现。