【问题标题】:How to iterate hashmap in reverse order in Java如何在Java中以相反的顺序迭代hashmap
【发布时间】:2012-05-22 16:38:01
【问题描述】:

我尝试了几个小时,但没有找到任何最佳方法来实现反向哈希图的迭代,这就是我拥有的哈希图。

      Map<Integer, List<String>> map = new HashMap<Integer, List<String>>();

             for(Integer key : map.keySet()) {
                List<String> value = map.get(key);
                List<Map<String,?>> security = new LinkedList<Map<String,?>>();  
                for(int ixy = 0; ixy < value.size()-1; ixy++){
                    security.add(createItem(value.get(ixy), value.get(ixy+1))); 
                }
                adapter.addSection(Integer.toString(key), new SimpleAdapter(getApplicationContext(), security, R.layout.list_complex, new String[] { ITEM_TITLE, ITEM_CAPTION }, new int[] { R.id.list_complex_title, R.id.list_complex_caption }));  
            }

我也看过 TreeMap 的例子,

             Map<Integer, List<String>> sortedMap = new TreeMap<Integer, List<String>>(map);

但是树形图也以升序排列,我想要的是降序排列。

【问题讨论】:

标签: java hashmap


【解决方案1】:

实现hashmap逆序迭代的最佳方法

HashMap 没有定义其元素的任何特定顺序。因此也没有定义“反向”顺序。

对于TreeMap,您可以使用descendingMap()

【讨论】:

    【解决方案2】:

    由于this,您不能反向迭代HashMap

    这个类不保证地图的顺序;在 特别是,它不保证订单将保持不变 随着时间的推移。

    你应该使用LinkedHashMap:

    此实现与 HashMap 的不同之处在于它维护了一个 双向链表贯穿其所有条目。这个链接 list 定义迭代顺序,通常是 哪些键被插入到地图中(插入顺序)。注意 如果将键重新插入映射中,则插入顺序不受影响。 (如果 m.put(k, v) 在 m.containsKey(k) 会在 调用。)

    【讨论】:

    • 不幸的是,即使 JDK LinkedHashMap 也无法轻松访问其内部双链表以允许您以“相反的顺序”遍历,所以我想您基本上必须“自己动手”(不幸的是,链表与 HashMap 组合)类。番石榴可能有一些帮助......
    • 不幸的是,即使是 JDK LinkedHashMap 也无法轻松访问其内部双链表以允许您以“逆序”遍历另请参阅 stackoverflow.com/a/1936472/32453
    【解决方案3】:

    也许你需要一个NavigableMap,比如 TreeMap。

    【讨论】:

      【解决方案4】:

      HashMap 不维护键之间的任何顺序。

      TreeMap 按照它们的自然顺序或由您在构建映射时传递的比较器强加的顺序对其键进行排序。因此,如果您希望整数键以相反的顺序排列,请以这种方式构造 TreeMap:

      Map<Integer, List<String>> sortedMap = 
          new TreeMap<Integer, List<String>>(Collections.reverseOrder());
      

      【讨论】:

      • 方法也不错,虽然我觉得TreeMap#descendingMap() 更优雅。 U_U
      【解决方案5】:

      hashmap 不是有序集合。改用 TreeMap,它具有用于反向迭代的 descendingKeySet。请参阅javadocsLinkedHashMap也是不错的选择。

      【讨论】:

        【解决方案6】:
        Map<Integer, List<String>> sortedMap = new TreeMap<Integer, List<String>>(Collections.reverseOrder());
        
        Collections.reverseOrder() keeps the map sorted in descending order.
        

        【讨论】:

          【解决方案7】:

          但是树形图也按升序排列,我想要的是降序排列。

          实现一个Comparator,将其与自然顺序进行反向比较,然后正常迭代,您将进行反向迭代

          【讨论】:

            【解决方案8】:

            Hashmap 没有特定的顺序。但是你可以使用 TreeMap。

            也许这个简单的例子可以帮助你:

            Map<Integer, String> map = new TreeMap<Integer, String>();
                    map.put(1, "abc1");
                    map.put(2, "abc2");
                    map.put(3, "abc3");
            
                    ArrayList<Integer> keys = new ArrayList<Integer>(map.keySet());
                    for(int i=keys.size()-1; i>=0;i--){
                        System.out.println(map.get(keys.get(i)));
                    }
            

            【讨论】:

            • 请注意,这种方法在内存使用和时间复杂度方面都相当低效。
            • NPE 的回答似乎更合适,因为它不需要创建 ArrayList 所需的空间/时间`
            • 我不喜欢这样,因为它依赖于键空间中的整数值。我实际上更喜欢 JB Nizet 的颠倒默认排序顺序的答案,这样,无论您的键空间中的值类型如何,您都可以遍历键。
            【解决方案9】:

            你可以使用TreeMap#descendingKeySet方法。

            Map<Integer, List<String>> map = new TreeMap<Integer, List<String>>();
            
            for(Integer key : map.descendingKeySet()) {
                List<String> value = map.get(key);
                List<Map<String,?>> security = new LinkedList<Map<String,?>>();  
                for(int ixy = 0; ixy < value.size()-1; ixy++){
                    security.add(createItem(value.get(ixy), value.get(ixy+1))); 
                }
                adapter.addSection(Integer.toString(key), new SimpleAdapter(getApplicationContext(), security, R.layout.list_complex, new String[] { ITEM_TITLE, ITEM_CAPTION }, new int[] { R.id.list_complex_title, R.id.list_complex_caption }));
            } 
            

            参考

            https://docs.oracle.com/javase/8/docs/api/java/util/TreeMap.html#descendingKeySet--

            【讨论】:

              【解决方案10】:
                  TreeMap<Integer, String> map = new TreeMap<Integer, String>();
                  map.put(1, "abc1");
                  map.put(2, "abc2");
                  map.put(3, "abc3");
                  NavigableMap<Integer, String> nmap = map.descendingMap();
                  for (NavigableMap.Entry<Integer, String> entry : nmap.entrySet()) {
                      System.out.println("Key : " + entry.getKey() + " Value : " + entry.getValue());
                  }
              

              NPE 思想的实现。

              【讨论】:

                【解决方案11】:

                使用 insted:

                new TreeMap<>(Collections.reverseOrder())
                

                你会得到你想要的。

                【讨论】:

                  【解决方案12】:

                  我发现迭代器通过以下方式从 Java Hashtable 获得: Hashtable.values().iterator() 和 Hashtable.keys().asIterator() 默认情况下都是相反的顺序。一个奇怪的是,values().iterator 的第一个最终值为“0”,我在填充它时没有添加它。

                  【讨论】:

                    猜你喜欢
                    • 2015-12-09
                    • 1970-01-01
                    • 2012-01-09
                    • 2019-01-15
                    • 2017-05-28
                    • 2018-08-08
                    • 1970-01-01
                    • 1970-01-01
                    • 1970-01-01
                    相关资源
                    最近更新 更多