对基于Value的HashMap进行排序然后键入? [英] Sorting a HashMap based on Value then Key?

查看:109
本文介绍了对基于Value的HashMap进行排序然后键入?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


可能存在重复:

如何对Map< Key,Value>进行排序在Java中的值?


我有一个类型的HashMap:

  HashMap< String,Integer> h = new HashMap< String,Integer>(); 

HashMap包含一个字符串列表,Integer是一个计数器,被发现。我希望能够做到的是对基于整数的HashMap进行排序,然后按照字符串的字母顺序进行排序。

目前我保持一条记录(变量命名为max)的最大值,并显示如下值:

  public void print(){
while(max> 0){
for(String key:h.keySet()){
if(h.get(key)== max){
System。 out.println(key ++ h.get(key));
}
}
max--;
}
}

不按字母顺序排列值访问HashMap max * h(大小)次。



有什么更好的解决方案?

解决方案

下面是一个 Comparator ,它用排序 Map.Entry 对象Comparable 键和值:

  public class ValueThenKeyComparator< K extends Comparable< ;? super K>,
V延伸可比较< ;? super V>>
实现比较器< Map.Entry< K,V>> {

public int compare(Map.Entry< K,V> a,Map.Entry< K,V> b){
int cmp1 = a.getValue()。compareTo(b .getValue());
if(cmp1!= 0){
return cmp1;
} else {
return a.getKey()。compareTo(b.getKey());



$ b $ / code $ / pre
$ b $ p < d将所有映射条目放入列表中,然后对其进行排序:

  List< Map.Entry< String,Integer>> ; list = new ArrayList< Map.Entry< String,Integer>>(h.entrySet()); 
Collections.sort(list,new ValueThenKeyComparator< String,Integer>());


Possible Duplicate:
How to sort a Map<Key, Value> on the values in Java?

I have a HashMap of the type:

HashMap<String, Integer> h = new HashMap<String, Integer>();

The HashMap contains a list of Strings and the Integer is a counter for the number of times that String has been found. What I would like to be able to do is sort the HashMap based on the Integers, then on the alphabetical order of the Strings.

At the moment I am keeping a record of the largest occurrence of a word (variable named max) and displaying the values as follows:

public void print(){
    while(max > 0){
       for (String key : h.keySet()){
           if(h.get(key) == max){
               System.out.println(key + " " + h.get(key));
           }
       }
       max--;
    }
}

Which doesn't sort the values alphabetically, also it accesses the HashMap max*h(size) times.

What is the better solution?

解决方案

Here's a Comparator that sorts Map.Entry objects with Comparable keys and values:

public class ValueThenKeyComparator<K extends Comparable<? super K>,
                                    V extends Comparable<? super V>>
    implements Comparator<Map.Entry<K, V>> {

    public int compare(Map.Entry<K, V> a, Map.Entry<K, V> b) {
        int cmp1 = a.getValue().compareTo(b.getValue());
        if (cmp1 != 0) {
            return cmp1;
        } else {
            return a.getKey().compareTo(b.getKey());
        }
    }

}

You'd put all of the map entries into a list and then sort that:

List<Map.Entry<String, Integer>> list = new ArrayList<Map.Entry<String, Integer>>(h.entrySet());
Collections.sort(list, new ValueThenKeyComparator<String, Integer>());

这篇关于对基于Value的HashMap进行排序然后键入?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆