Search code examples
javadata-structurescollectionsguava

Collection that prevents duplicates but preserves reversible duplicate insertion order?


Is there a collection that preserves reversible duplicate insertion order?

Specifically, if I insert the following items:

1
2
3
1

I want to be able to iterate over them and receive them in the following order:

1
3
2

That is, I want them in descending insertion order with duplicate insertions causing a reorder. Guava's LinkedListMultimap is the closest I've found, but it doesn't support descending traversal.

Java's LinkedHashSet doesn't work because it doesn't allow descending traversal.

I could also use an LRU cache, but most LRU libraries I've found don't support retrieving objects in LRU order.

Does this thing have a standard name?


Solution

  • Try ListOrderedSet class of org.apache.commons.collections4.set.

    For example:

    listOrderedSet.add(1,1);
    listOrderedSet.add(1,2);
    listOrderedSet.add(1,3);
    listOrderedSet.add(1,1);  
    

    This will give you the expected out put.