如何反向遍历链接哈希映射? [英] How to traverse Linked Hash Map in reverse?
本文介绍了如何反向遍历链接哈希映射?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
可能重复:
以相反的顺序迭代LinkedHashMap
如何以相反的顺序遍历链接的哈希映射?地图中有预定义的方法吗?
How to traverse Linked Hash Map in a reverse order? Is there any predefined method in map to do that?
我按如下方式创建它:
LinkedHashMap<Integer, String> map = new LinkedHashMap<Integer,String>();
map.put(1, "one");
map.put(2, "two");
map.put(3, "three");
推荐答案
List<Entry<Integer,String>> list = new ArrayList<>(map.entries());
for( int i = list.size() -1; i >= 0 ; i --){
Entry<Integer,String> entry = list.get(i);
}
不是很漂亮,而且代价是条目集的副本,如果您的地图有大量条目可能是个问题。
Not really pretty and at the cost of a copy of the entry set, which if your map has a significant number of entries might be a problem.
excellant Guava库有一个 [List.reverse(List<>)] [2]
,它允许你为每个使用Java 5样式循环而不是索引循环:
The excellant Guava library have a [List.reverse(List<>)][2]
that would allow you to use the Java 5 for each style loop rather than the indexed loop:
//using guava
for( Entry entry : Lists.reverse(list) ){
// much nicer
}
这篇关于如何反向遍历链接哈希映射?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文