如何在Java中以相反的顺序迭代哈希映射

2022-09-01 21:28:13

我正在尝试一个小时,但没有找到任何最佳方法来以相反的顺序实现哈希映射的迭代,这就是我拥有的哈希映射。

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

我也看过树图的例子,

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

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


答案 1

以相反的顺序实现哈希映射迭代的最佳方法

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

对于 ,您可以使用降序 Map()。TreeMap


答案 2

哈希映射没有特定的顺序。但是您可以使用树状图。

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

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