How can I sort a ConcurrentHashMap by values?

后端 未结 3 903
南方客
南方客 2021-01-16 14:59
ConcurrentHashMap pl = new ConcurrentHashMap<>();
pl.put(\"joker25\", 255);
pl.put(\"minas\", 55);
pl.put(\"agoriraso\", 122);
pl.put(\"p         


        
3条回答
  •  情书的邮戳
    2021-01-16 15:42

    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 pl = ....
    List values = new ArrayList<>(pl.keySet());
    Collections.sort(values, new Comparator() {
      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));
    }
    

提交回复
热议问题