如何给一个map按照key对应的value值排序

博客直接分享了代码,输出了结果,代码转载自https://www.cnblogs.com/devin-sl/p/10557400.html ,涉及C/C++相关内容。

直接上代码:

public static void main(String[] args) {
        HashMap<String, Integer> map = new HashMap<String, Integer>();
        for(int i=0;i<10;i++) {
       //添加key,并随机添加key对应value的integer值 map.put(
"aa" + i, (int)(Math.random()*1000)); } List<Map.Entry<String,Integer>> list = new ArrayList<Map.Entry<String,Integer>>(map.entrySet());
     //升序排列逻辑 Collections.sort(list,
new Comparator<Map.Entry<String,Integer>>() { public int compare(Entry<String, Integer> o1, Entry<String, Integer> o2) { return o1.getValue().compareTo(o2.getValue()); } });
     //打印输出结果
for(Map.Entry<String,Integer> mapping:list){ System.out.println(mapping.getKey() + "---:---" + mapping.getValue()); } }

输出结果如下:

aa7---:---7
aa5---:---27
aa1---:---77
aa9---:---140
aa0---:---194
aa4---:---445
aa3---:---531
aa2---:---566
aa8---:---631
aa6---:---992

 

转载于:https://www.cnblogs.com/devin-sl/p/10557400.html

要在Map中找出最大的三个value对应key,可以按照以下步骤操作: 1. 首先,创建一个优先级队列(PriorityQueue),它会自动排序插入元素,你可以通过Comparator指定降序排列。 2. 然后遍历map,将每个value添加到优先级队列中。如果队列大小超过3,就弹出最小的元素(即当前最大已不再是最前三个)。同时记录下此时队列顶部的键对,因为它们是当前找到的最大三个value。 3. 最终,队列的顶部三个键就是你需要的结果。 这里是一个简单的伪代码示例: ```java import java.util.*; import java.util.concurrent.PriorityBlockingQueue; Map<KeyType, ValueType> map; // 创建一个最大容量为3的优先级队列 PriorityQueue<Map.Entry<KeyType, ValueType>> maxValues = new PriorityQueue<>( (a, b) -> b.getValue().compareTo(a.getValue()), new Comparator<Map.Entry<KeyType,ValueType>>() { @Override public int compare(Map.Entry<KeyType, ValueType> a, Map.Entry<KeyType, ValueType> b) { return a.getValue().compareTo(b.getValue()); } }, 3 // 设置容量为3 ); // 遍历map for (Map.Entry<KeyType, ValueType> entry : map.entrySet()) { // 如果队列满,移除最小的元素 if (maxValues.size() == 3) { maxValues.poll(); } // 插入新的元素 maxValues.offer(entry); } // 获取并打印出最大三个value对应key List<KeyType> topThreeKeys = new ArrayList<>(); while (!maxValues.isEmpty()) { topThreeKeys.add(maxValues.poll().getKey()); } topThreeKeys.forEach(key -> System.out.println("Key with largest value: " + key)); ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值