2012-10-16 38 views
4

我有以下HashMap如何根据它们的值对HashMap的元素进行排序?

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

什么是根据价值来订购吧最简单的方法?

+1

您不能对一个HashMap,你可以使用左右一个TreeMap但是键和值必须在其他的方式为您的要求。 –

+0

请忽略我之前评论中的建议。这样做的问题是,总会有多个条目具有相同计数的可能性,并且映射不允许重复键。我认为最好的做法是按照排序条目列表中的建议来回答问题。 –

+0

如果你不限制使用'HashMap',为什么不创建一个包含你的词作为'String'的类,你的计数是'int',并且让它实现Comparable来找到最大值,然后只需要将所有这些对象插入到最大堆中,并找到堆的根节点? –

回答

8

您无法按值排序Map,尤其是不能排序的HashMap,根本无法排序。

相反,你可以在条目排序:

List<Map.Entry<String, Integer>> entries = new ArrayList<Map.Entry<String, Integer>>(map.entrySet()); 
Collections.sort(entries, new Comparator<Map.Entry<String, Integer>>() { 
    public int compare(
     Map.Entry<String, Integer> entry1, Map.Entry<String, Integer> entry2) { 
    return entry1.getValue().compareTo(entry2.getValue()); 
    } 
}); 

将上升计数的顺序排序条目。

0

解决办法,如果你想他们按顺序打印(不存储)。

  1. 创建一个新地图(tempMap)并将您的值作为键和键作为值。要使密钥具有唯一性,请在每个密钥中添加一些唯一值,例如key1 = value1 + @ 0。

  2. 获取值的列表,如map.values()名单myVlues

  3. 排序myVlues列表作为Collections.sort(myVlues)

  4. 现在迭代myVlues,得到tempMap相应key,例如恢复密钥key.substring(0,key.length-2)并打印键和值对。

希望这会有所帮助。

1

A TreeMap可以按照Comparator定义的顺序保存其条目。

  1. 我们可以创建一个比较器,通过首先放置最大值来排序Map。
  2. 然后,我们将构建一个使用该比较器的TreeMap。
  3. 然后我们将把我们的counts地图中的所有条目放入比较器中。
  4. 最后,我们将get the first key放在地图上,它应该是最常用的单词(或者至少其中一个,如果多个单词有相同的计数)。

    public class Testing { 
        public static void main(String[] args) { 
    
         HashMap<String,Double> counts = new HashMap<String,Integer>(); 
    
         // Sample word counts 
         counts.put("the", 100); 
         counts.put("pineapple",5); 
         counts.put("a", 50); 
    
         // Step 1: Create a Comparator that order by value with greatest value first 
         MostCommonValueFirst mostCommonValueFirst = new MostCommonValueFirst(counts); 
    
         // Step 2: Build a TreeMap that uses that Comparator 
         TreeMap<String,Double> sortedMap = new TreeMap<String,Integer (mostCommonValueFirst); 
    
         // Step 3: Populate TreeMap with values from the counts map 
         sortedMap.putAll(counts); 
    
         // Step 4: The first key in the map is the most commonly used word 
         System.out.println("Most common word: " + sortedMap.firstKey()); 
        } 
    } 
    
    private class MostCommonValueFirst implements Comparator<String> { 
        Map<String, Integer> base; 
    
        public MostCommonValueFirst(Map<String, Integer> base) { 
         this.base = base; 
        } 
    
        // Note: this comparator imposes orderings that are inconsistent with equals.  
        public int compare(String a, String b) { 
         if (base.get(a) >= base.get(b)) { 
          return 1; 
         } else { 
         return -1; 
         } // returning 0 would merge keys 
        } 
    } 
    

来源:https://stackoverflow.com/a/1283722/284685

+0

我不确定这是不是一个好主意。键的比较器顺序可以随着地图的值而改变。它本质上是一个可变键(就“TreeMap”而言)。 –

+0

同意,但我们完成填图后仍然可以做到。 – Adam

相关问题