How can I iterate through items of a LinkedHashSet
from the last item to the first one?
We can iterate through LinkedHashSet in reverse order. By converting LinkedHashSet into ArrayList and using Collections class' reverse() method. Method signature: public static void reverse(List list); This method is used to reverse the order of ArrayList contents i.e.; reverse-order of insertion-order.
We can iterate the list in reverse order in two ways: Using List. listIterator() and Using for loop method.
Iterate through the elements of LinkedHashSet using the iterator method. We will use the hasNext() method and the next() method along with the while loop to iterate through LinkedHashSet elements. Type Parameters: E – the type of elements maintained by this set.
Syntax: LinkedList<String> linkedlist = new LinkedList<>(); Iterator<String> listIterator = linkedlist. descendingIterator();
If you want to continue to use collections, you could use the following:
LinkedHashSet<T> set = ... LinkedList<T> list = new LinkedList<>(set); Iterator<T> itr = list.descendingIterator(); while(itr.hasNext()) { T item = itr.next(); // do something }
If you're fine with using an array instead, you could take a look at hvgotcodes' answer.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With