Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 773
rafakob Avatar asked Apr 04 '16 10:04

rafakob


People also ask

Does LinkedHashSet maintain insertion order?

LinkedHashSet maintains insertion order, just like an ArrayList .

How does LinkedHashSet maintain order?

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.

Does LinkedHashSet allow duplicates?

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).

Is LinkedHashSet ordered and unique?

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.


1 Answers

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;     }  } 
like image 177
OldCurmudgeon Avatar answered Sep 21 '22 18:09

OldCurmudgeon