如何按值对ConcurrentHashMap进行排序?

时间:2014-04-22 17:15:47

标签: java sorting

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进行排序?

minas,25
agoriraso,122
joker25,255
pigasakias,1024
geo5,5092

我该怎么做?

4 个答案:

答案 0 :(得分:1)

由于ConcurrentHashMap不保证订购,因此您必须将项目转储到列表中然后对其进行排序。例如:

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));
}

答案 1 :(得分:0)

LinkedList<Map.Entry<String, Integer>> list = new LinkedList<>(counter.entrySet());
Comparator<Map.Entry<String, Integer>> comparator = Comparator.comparing(Map.Entry::getValue);
Collections.sort(list, comparator.reversed());

Map<String, BigDecimal> reMap = new LinkedHashMap<>();
counter.entrySet().stream()
    .sorted(Map.Entry.<String, BigDecimal>comparingByValue().reversed())
    .forEachOrdered(eachOne -> reMap.put(eachOne.getKey(), eachOne.getValue()));

答案 2 :(得分:0)

您可以使用列表存储EntrySet值,然后在Comparator的帮助下使用list.sort()方法进行排序。

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);

//Add your map elements into a list which accepts EntrySet<String, Integer> as Input
List<Entry<String, Integer>> list = new ArrayList<>(pl.entrySet());

//Sort the list by using comparator object or comparator lambda expression
list.sort((e1, e2) -> e1.getValue().compareTo(e2.getValue()));

//create a new HashMap and add the values to it, but here if you add the 
//sorted values to Concurrent hashMap you will not see the values in 
//sorted order because the entries will be stored according to hashvalue of string

//Suggest you to use the linked hashmap if you want to see the sorted order of entries according to the valueset
ConcurrentHashMap<String,Integer> ol = new ConcurrentHashMap<>();

//LinkedHashMap<String,Integer> ol = new LinkedHashMap<>();

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

答案 3 :(得分:0)

我们可以使用 Java 流轻松地按排序顺序遍历 Number

ConcurrentHashMap