Search code examples
javacollectionslinked-listiterationhashset

The Java LinkedHashSet uses a doubly-linked list. Can it also be iterated backwards?


Oracle-Documentation says following about LinkedHashSet: "Hash table and linked list implementation of the Set interface, with predictable iteration order. This implementation differs from HashSet in that it maintains a doubly-linked list running through all of its entries."

The iterator you can get is in insertion order. Iteration in reverse-insertion order would also be technicially feasable thought, as it's a doubly-linked.

Can such a reverse-Iterator be created (or even a ListIterator which does both)?


Solution

  • LinkedHashSet doesn't expose any API to iterate over it backwards. Although this would have a really bad performance impact, you could copy the LinkedHashSet to a List (retaining its order) and then iterate backwards on it:

    LinkedHashSet<SomeClass> myLinkedHashSet = ...;
    List<SomeClass> myList = new ArrayList<>(myLinkedHashSet); // Order is retained
    ListIterator<SomeClass> myIter = myList.listIterator(myList.size());
    while (myIter.hasPrevious()) {
        System.out.println(myIter.previous());
    }