如何按值对ConcurrentHashMap排序? [英] How can I sort a ConcurrentHashMap by values?
本文介绍了如何按值对ConcurrentHashMap排序?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
ConcurrentHashMap<String,Integer> pl = new ConcurrentHashMap<>();
pl.put("joker25", 255);
pl.put("minas", 55);
pl.put("agoriraso", 122);
pl.put("pigasakias", 1024);
pl.put("geo5", 5092);
我已经搜索了,但找不到任何东西.如何按值对ConcurrentHashMap排序?
I've searched and I can't find anything. How do I sort my ConcurrentHashMap by values?
minas,25
agoriraso,122
joker25,255
pigasakias,1024
geo5,5092
我该怎么做?
推荐答案
由于ConcurrentHashMap
不保证订购,因此您必须将这些项目转储到列表中然后进行排序.例如:
Since ConcurrentHashMap
makes no guarantees about ordering you'll have to dump the items into a list and then sort that. For example:
final Map<String, Integer> pl = ....
List<String> values = new ArrayList<>(pl.keySet());
Collections.sort(values, new Comparator<String>() {
public int compare(String a, String b) {
// no need to worry about nulls as we know a and b are both in pl
return pl.get(a) - pl.get(b);
}
});
for(String val : values) {
System.out.println(val + "," + pl.get(val));
}
这篇关于如何按值对ConcurrentHashMap排序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文