如何在Java中以相反的顺序迭代hashmap [英] How to iterate hashmap in reverse order in Java

查看:24
本文介绍了如何在Java中以相反的顺序迭代hashmap的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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<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 的例子,

I have seen example of TreeMap as well,

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

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

But treemap also gives in ascending order, what I want is in descending order.

推荐答案

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

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

这篇关于如何在Java中以相反的顺序迭代hashmap的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆