Java LinkedHashSet backwards iteration

David Weng picture David Weng · May 24, 2012 · Viewed 22.7k times · Source

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

Answer

Jeffrey picture Jeffrey · May 24, 2012

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.