Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java LinkedHashSet backwards iteration

Tags:

How can I iterate through items of a LinkedHashSet from the last item to the first one?

like image 259
David Weng Avatar asked May 24 '12 16:05

David Weng


People also ask

How do you reverse a LinkedHashSet in Java?

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.

Can you iterate backwards in Java?

We can iterate the list in reverse order in two ways: Using List. listIterator() and Using for loop method.

How do I loop through a LinkedHashSet?

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.

How do you iterate through a linked list backwards?

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


1 Answers

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.

like image 153
Jeffrey Avatar answered Sep 22 '22 00:09

Jeffrey