How to traverse Linked Hash Map in reverse? [duplicate]

感情迁移 提交于 2020-01-09 07:16:47

问题


Possible Duplicate:
Iterating through a LinkedHashMap in reverse order

How to traverse Linked Hash Map in a reverse order? Is there any predefined method in map to do that?

I'm creating it as follows:

LinkedHashMap<Integer, String> map = new LinkedHashMap<Integer,String>();
map.put(1, "one");
map.put(2, "two");
map.put(3, "three");

回答1:


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.

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
}



回答2:


Try this, it will print the keys in reverse insertion order:

ListIterator<Integer> iter =
    new ArrayList<>(map.keySet()).listIterator(map.size());

while (iter.hasPrevious()) {
    Integer key = iter.previous();
    System.out.println(key);
}

You can also iterate by the reverse insertion order of entries:

ListIterator<Map.Entry<Integer, String>> iter =
    new ArrayList<>(map.entrySet()).listIterator(map.size());

while (iter.hasPrevious()) {
    Map.Entry<Integer, String> entry = iter.previous();
    System.out.println(entry.getKey() + ":" + entry.getValue());
}



回答3:


Guava RULES:

List<Object> reverseList = Lists.reverse(
        Lists.newArrayList(map.keySet()));

Lists.reverse



来源:https://stackoverflow.com/questions/8893231/how-to-traverse-linked-hash-map-in-reverse

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!