javalistlinkedhashset

LinkedHashSet - insertion order and duplicates - keep newest "on top"


I need a collection that keeps insertion order and has unique values. LinkedHashSet looks like the way to go, but there's one problem - when two items are equal, it removes the newest one (which makes sense), here's an example:

set.add("one");
set.add("two");
set.add("three");
set.add("two");

The LinkedHashSet will print:

one, two, three

But what I need is:

one, three, two

What would be the best solution here? Is there any collection/collections method that can do this or should I implement it manually?


Solution

  • Most of the Java Collections can be extended for tweaking.

    Subclass LinkedHashSet, overriding the add method.

    class TweakedHashSet<T> extends LinkedHashSet<T> {
    
        @Override
        public boolean add(T e) {
            // Get rid of old one.
            boolean wasThere = remove(e);
            // Add it.
            super.add(e);
            // Contract is "true if this set did not already contain the specified element"
            return !wasThere;
        }
    
    }