How to iterate hashmap in reverse order in Java

后端 未结 12 1158
别那么骄傲
别那么骄傲 2020-12-30 01:08

I am trying this for some hour but not finding any best approach to achieve iteration of hashmap in reverse order, this is the hashmap I have.

      Map

        
相关标签:
12条回答
  • 2020-12-30 02:08

    A HashMap doesn't maintain eny order between keys.

    A TreeMap orders its keys by their natural order, or by the order imposed by a comparator that you pass when constructing the map. So if you want to have Integer keys ordered in reverse order, construct the TreeMap this way:

    Map<Integer, List<String>> sortedMap = 
        new TreeMap<Integer, List<String>>(Collections.reverseOrder());
    
    0 讨论(0)
  • 2020-12-30 02:08
    Map<Integer, List<String>> sortedMap = new TreeMap<Integer, List<String>>(Collections.reverseOrder());
    
    Collections.reverseOrder() keeps the map sorted in descending order.
    
    0 讨论(0)
  • 2020-12-30 02:08

    The hashmap is not an ordered collection. Use TreeMap instead, which has descendingKeySet for reverse iteration. See the javadocs. LinkedHashMap is also a good choice.

    0 讨论(0)
  • 2020-12-30 02:09

    Hashmap does not have specific order. But you can use TreeMap.

    Perhaps this simple example can help you :

    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)));
            }
    
    0 讨论(0)
  • 2020-12-30 02:13

    best approach to acheive iteration of hashmap in reverse order

    HashMap does not define any particular ordering of its element. Therefore the "reverse" order isn't defined either.

    For a TreeMap, you can use descendingMap().

    0 讨论(0)
  • 2020-12-30 02:14

    You can't iterate over a HashMap in reverse because of this:

    This class makes no guarantees as to the order of the map; in particular, it does not guarantee that the order will remain constant over time.

    What you should use is a LinkedHashMap:

    This implementation differs from HashMap in that it maintains a doubly-linked list running through all of its entries. This linked list defines the iteration ordering, which is normally the order in which keys were inserted into the map (insertion-order). Note that insertion order is not affected if a key is re-inserted into the map. (A key k is reinserted into a map m if m.put(k, v) is invoked when m.containsKey(k) would return true immediately prior to the invocation.)

    0 讨论(0)
提交回复
热议问题