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

泄露秘密 提交于 2019-11-27 21:22:37
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
}

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

Guava RULES:

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

Lists.reverse

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