如何在Java中以相反的顺序迭代hashmap

Pro*_*mer 18 java hashmap

我试了几个小时,但没有找到任何最好的方法来以相反的顺序实现hashmap的迭代,这是我的hashmap.

      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 }));  
            }
Run Code Online (Sandbox Code Playgroud)

我也见过TreeMap的例子,

             Map<Integer, List<String>> sortedMap = new TreeMap<Integer, List<String>>(map);
Run Code Online (Sandbox Code Playgroud)

但是树形图也按升序给出,我想要的是降序.

NPE*_*NPE 46

以相反顺序实现hashmap迭代迭代的最佳方法

HashMap没有定义其元素的任何特定顺序.因此,也没有定义"反向"顺序.

对于a TreeMap,你可以使用descendingMap().

  • DescendingMap()看起来不错。+1 (2认同)

Ksh*_*tij 19

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)));
        }
Run Code Online (Sandbox Code Playgroud)

  • 请注意,就内存使用和时间复杂性而言,此方法效率较低. (6认同)

JB *_*zet 11

HashMap不会在键之间维护eny顺序.

TreeMap按其自然顺序或按构造地图时传递的比较器强加的顺序对其键进行排序.因此,如果您想以相反的顺序排序Integer键,请以这种方式构造TreeMap:

Map<Integer, List<String>> sortedMap = 
    new TreeMap<Integer, List<String>>(Collections.reverseOrder());
Run Code Online (Sandbox Code Playgroud)


Rav*_*ain 6

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

Collections.reverseOrder() keeps the map sorted in descending order.
Run Code Online (Sandbox Code Playgroud)


Sub*_*der 6

你可以使用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 }));
} 
Run Code Online (Sandbox Code Playgroud)

参考:

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