7

我有以下内容HashMap

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

根据值订购它的最简单方法是什么?

4

4 回答 4

9

您不能Map按值对 a 进行排序,尤其是 a 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());
  }
});

将按计数升序对条目进行排序。

于 2012-10-16T16:57:47.717 回答
4

您可以使用 . 从地图中获取一组条目 ( Setof ) 。只需遍历它们,并通过 . 检查值。Map.Entrymap.entrySet()getValue()

于 2012-10-16T16:55:12.820 回答
1

一个解决方法,如果你想让他们按顺序打印它们(不存储)。

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

  2. 获取值map.values()列表作为列表myVlues

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

  4. 现在迭代myVlues,获取对应key的 from tempMap,恢复键,例如 key.substring(0, key.length-2) 并打印键和值对。

希望这可以帮助。

于 2012-10-16T17:04:34.610 回答
1

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

  1. 我们可以创建一个比较器,通过将最大值放在首位来对 Map 进行排序。
  2. 然后,我们将构建一个使用该比较器的 TreeMap。
  3. 然后,我们将把counts地图中的所有条目放入比较器中。
  4. 最后,我们将获得地图中的第一个键,它应该是最常见的词(或者至少其中一个,如果多个词具有相同的计数)。

    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

于 2012-10-16T17:07:32.347 回答