JDK-8170438 : Reverse Iteration of LinkedHashSet
  • Type: Enhancement
  • Component: core-libs
  • Sub-Component: java.util:collections
  • Affected Version: 8,9
  • Priority: P4
  • Status: Open
  • Resolution: Unresolved
  • OS: generic
  • CPU: generic
  • Submitted: 2016-11-27
  • Updated: 2016-11-29
Related Reports
Duplicate :  
Relates :  
Relates :  
Description
A DESCRIPTION OF THE REQUEST :
I would like LinkedHashSet to provide a descendingIterator() method like LinkedList does.

Thank you for your consideration.

JUSTIFICATION :
Many times it would be useful to iterate over a LinkedHashSet in reverse. This would allow for the LinkedHashSet to support deque-like behavior while allowing for fast access to entries in the set. The current implementation already "maintains a doubly-linked list running through all of its entries." Thus support for reverse iteration, like LinkedList, should be relatively easy to provide. 


CUSTOMER SUBMITTED WORKAROUND :
One workaround is

LinkedHashSet<T> set = ...

LinkedList<T> list = new LinkedList<>(set);
Iterator<T> itr = list.descendingIterator();
while(itr.hasNext()) {
    T item = itr.next();
    // do something
}

However, this makes a copy of the items in the set and is not practical for large sets. My current workaround is to build my own Collection, which is less desirable than a solution given directly by the SDK. 


Comments
It seems reasonable to have more universal versions of existing collection classes. Any class (like LinkedList) based on double-linked nodes can perhaps easily implement List and Deque. There is the reverse feature of adding List to ArrayDeque. But usually there is some blocker that prevents implementation of additional interfaces in a completely compatible way, and there is usually resistance to adding methods from some interface without actually implementing the full interface.
29-11-2016