Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a way to create a List/Set which keeps insertion order and does not allow duplicates in Java?

Tags:

java

list

set

What is the most efficient way of maintaining a list that does not allow duplicates, but maintains insertion order and also allows the retrieval of the last inserted element in Java?

like image 615
Wayne Avatar asked Jan 19 '23 22:01

Wayne


1 Answers

Try LinkedHashSet, which keeps the order of input.

Note that re-inserting an element would update its position in the input order, thus you might first try and check whether the element is already contained in the set.

Edit:

You could also try the Apache commons collections class ListOrderedSet which according to the JavaDoc (if I didn't missread anything again :) ) would decorate a set in order to keep insertion order and provides a get(index) method.

Thus, it seems you can get what you want by using new ListOrderedSet(new HashSet());

Unfortunately this class doesn't provide a generic parameter, but it might get you started.

Edit 2:

Here's a project that seems to represent commons collections with generics, i.e. it has a ListOrderedSet<E> and thus you could for example call new ListOrderedSet<String>(new HashSet<String>());

like image 70
Thomas Avatar answered Jan 22 '23 10:01

Thomas