How to iterate hashmap in reverse order in Java

后端 未结 12 1157
别那么骄傲
别那么骄傲 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 01:50

    Perhaps you need a NavigableMap, like a TreeMap.

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

    An implementation of NPE idea.

    0 讨论(0)
  • 2020-12-30 01:53

    But treemap also gives in asecding order, what i want is in descending order.

    Implement a Comparator that will compare it reverse than natural order and then just iterate normally you will have reverse iteration

    0 讨论(0)
  • 2020-12-30 01:56

    I've found that the Iterators obtained from Java Hashtable via: Hashtable.values().iterator() and Hashtable.keys().asIterator() are both in reverse order by default. One oddity, The values().iterator has a first final value of "0" which I didn't add when populating it.

    0 讨论(0)
  • 2020-12-30 01:58

    Use insted:

    new TreeMap<>(Collections.reverseOrder())
    

    and you will get what you want.

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

    You can use TreeMap#descendingKeySet method.

    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 }));
    } 
    

    Reference:

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

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