javasetiterationlinkedhashset

Java LinkedHashSet backwards iteration


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


Solution

  • 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.