Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Iterating through a LinkedHashMap in reverse order

I have a LinkedHashMap:

LinkedHashMap<String, RecordItemElement> 

that I need to iterate through from a given key's position, backwards. So if I was given the 10th item's key, I'd need iterate backwards through the hashmap 9, 8, 7 etc.

like image 869
Dominic Bou-Samra Avatar asked Aug 24 '11 05:08

Dominic Bou-Samra


People also ask

How do you iterate through a linked list backwards?

Syntax: LinkedList<String> linkedlist = new LinkedList<>(); Iterator<String> listIterator = linkedlist. descendingIterator();

How do I loop through a LinkedHashMap?

There are basically two ways to iterate over LinkedHashMap:Using keySet() and get() Method. Using entrySet() and Iterator.

Can iterator go backwards?

C++ Iterators Reverse Iterators A reverse iterator is made from a bidirectional, or random access iterator which it keeps as a member which can be accessed through base() . To iterate backwards use rbegin() and rend() as the iterators for the end of the collection, and the start of the collection respectively.


2 Answers

The question requires a LinkedHashMap in reverse order, some answers suggesting using a TreeSet but this will reorder the map based upon the key.

This solution allows the iteration over the original LinkedHashMap not the new ArrayList as has also been proposed:

List<String> reverseOrderedKeys = new ArrayList<String>(linkedHashMap.keySet()); Collections.reverse(reverseOrderedKeys); for (String key : reverseOrderedKeys) {     RecordItemElement line = linkedHashMap.get(key); } 
like image 108
user2274508 Avatar answered Sep 21 '22 02:09

user2274508


The HashMap:

HashMap<Integer, String> map = new HashMap<Integer, String>(); 

Reverse iterating over values:

ListIterator<Sprite> iterator = new ArrayList<String>(map.values()).listIterator(map.size()); while (iterator.hasPrevious()) String value = iterator.previous(); 

Reverse iterating over keys:

ListIterator<Integer> iterator = new ArrayList(map.keySet()).listIterator(map.size()); while (iterator.hasPrevious()) Integer key = iterator.previous(); 

Reverse iterating over both:

ListIterator<Map.Entry<Integer, String>> iterator = new ArrayList<Map.Entry<Integer, String>>(map.entrySet()).listIterator(map.size()); while (iterator.hasPrevious()) Map.Entry<Integer, String> entry = iterator.previous(); 
like image 20
Ali Avatar answered Sep 21 '22 02:09

Ali