【问题标题】:How do I sort the elements of an HashMap according to their values? [duplicate]如何根据值对 HashMap 的元素进行排序? [复制]
【发布时间】:2012-10-06 20:17:49
【问题描述】:

我有以下HashMap

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

根据值排序的最简单方法是什么?

【问题讨论】:

  • 您不能对 HashMap 进行排序,您可以使用 TreeMap,但键和值必须相反才能满足您的要求。
  • 请忽略我之前评论中的建议。这样做的问题是,总会有多个条目具有相同的计数,并且地图不允许重复的键。我认为最好的方法是按照对条目列表进行排序的建议中的答案进行操作。
  • 如果您不限于使用HashMap,为什么不创建一个类,其中包含您的单词为String,您的计数为int,并让它实现Comparable to找到一个最大值,然后将所有这些对象插入到一个最大堆中,然后找到该堆的根节点?

标签: java sorting data-structures hashmap


【解决方案1】:

您可以使用 map.entrySet() 从映射中获取一组条目(SetMap.Entry)。只需遍历它们,然后检查 getValue() 的值。

【讨论】:

    【解决方案2】:

    您无法按值对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());
      }
    });
    

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

    【讨论】:

      【解决方案3】:

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

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

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

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

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

      希望这会有所帮助。

      【讨论】:

        【解决方案4】:

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

        1. 我们可以创建一个比较器,通过将最大值放在首位来对地图进行排序。
        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

        【讨论】:

        • 我不确定这是否是个好主意。键的比较器顺序可以随地图的值而变化。它本质上是一个可变键(就TreeMap 而言)。
        • 同意,但是在我们完成地图填充后我们仍然可以这样做。
        猜你喜欢
        • 2012-01-08
        • 2011-03-05
        • 1970-01-01
        • 1970-01-01
        • 2020-09-04
        • 2018-07-27
        • 2016-01-21
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多