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?
LinkedHashSet maintains insertion order, just like an ArrayList .
It preserves the order returned by the iterator of the collection as it interntally uses addAll : iterates over the specified collection, and adds each object returned by the iterator to this collection, in turn.
Duplicate values are not allowed in LinkedHashSet. One NULL element is allowed in LinkedHashSet. It is an ordered collection which is the order in which elements were inserted into the set (insertion-order).
The LinkedHashSet is an ordered version of HashSet that maintains a doubly-linked List across all elements. When the iteration order is needed to be maintained this class is used.
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; } }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With