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

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

问题描述






















$ b $ 映射<整数,列表< String>> map = new HashMap< Integer,List< String>>();

(Integer key:map.keySet()){
List< String> value = map.get(key);
列表< 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的例子,

 映射<整数,列表<字串>> sortedMap = new TreeMap< Integer,List< String>>(map); 

但是treemap也是按升序排列,我想要的是按降序排列。

解决方案

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



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

  Map< Integer,String> map = new TreeMap< Integer,String>(); 
map.put(1,abc1);
map.put(2,abc2);
map.put(3,abc3);

ArrayList<整数> keys = new ArrayList< Integer>(map.keySet());
for(int i = keys.size() - 1; i> = 0; i - ){
System.out.println(map.get(keys.get(i)));
}


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

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 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天全站免登陆