Take the 2-minute tour ×

How to create a Unique List in Java.

Right now I am using HashMap<String, Integer> to do this as the key is overwritten and hence at the end we can get HashMap.getKeySet() which would be unique. But I am sure there should be a better way to do this as the value part is wasted here.

share|improve this question

6 Answers 6

up vote 13 down vote accepted

You can use a Set implementation:

Some info from the JAVADoc:

A collection that contains no duplicate elements. More formally, sets contain no pair of elements e1 and e2 such that e1.equals(e2), and at most one null element. As implied by its name, this interface models the mathematical set abstraction.

Note: Great care must be exercised if mutable objects are used as set elements. The behavior of a set is not specified if the value of an object is changed in a manner that affects equals comparisons while the object is an element in the set. A special case of this prohibition is that it is not permissible for a set to contain itself as an element.`

These are the implementations:

  • HashSet

    This class offers constant time performance for the basic operations (add, remove, contains and size), assuming the hash function disperses the elements properly among the buckets. Iterating over this set requires time proportional to the sum of the HashSet instance's size (the number of elements) plus the "capacity" of the backing HashMap instance (the number of buckets). Thus, it's very important not to set the initial capacity too high (or the load factor too low) if iteration performance is important.

    When iterating a HashSet the order of the yielded elements is undefined.

  • LinkedHashSet

    Hash table and linked list implementation of the Set interface, with predictable iteration order. This implementation differs from HashSet in that it maintains a doubly-linked list running through all of its entries. This linked list defines the iteration ordering, which is the order in which elements were inserted into the set (insertion-order). Note that insertion order is not affected if an element is re-inserted into the set. (An element e is reinserted into a set s if s.add(e) is invoked when s.contains(e) would return true immediately prior to the invocation.)

    So, the output of the code above...

     Set<Integer> linkedHashSet = new LinkedHashSet<>();
     for (int i : linkedHashSet) {

    ...will necessarily be

  • TreeSet

    This implementation provides guaranteed log(n) time cost for the basic operations (add, remove and contains). By default he elements returned on iteration are sorted by their "natural ordering", so the code above...

     Set<Integer> treeSet = new TreeSet<>();
     for (int i : treeSet) {

    ...will output this:


    (You can also pass a Comparator instance to a TreeSet constructor, making it sort the elements in a different order.)

    Note that the ordering maintained by a set (whether or not an explicit comparator is provided) must be consistent with equals if it is to correctly implement the Set interface. (See Comparable or Comparator for a precise definition of consistent with equals.) This is so because the Set interface is defined in terms of the equals operation, but a TreeSet instance performs all element comparisons using its compareTo (or compare) method, so two elements that are deemed equal by this method are, from the standpoint of the set, equal. The behavior of a set is well-defined even if its ordering is inconsistent with equals; it just fails to obey the general contract of the Set interface.

share|improve this answer
Now I am confused, which one shall I use? I just need to have maintain a list of unique strings. So basically even when an existing string is added it should actually get added. –  user1804287 Nov 6 '12 at 21:25
i'll put the info in the answer, give me one minute –  Frank Nov 6 '12 at 21:26
Thanks in Advance :) –  user1804287 Nov 6 '12 at 21:26
The choice is yours...HashSet is universal and fast, treeset is ordered,LinkedHashset keeps insertion order... –  Frank Nov 6 '12 at 21:31
Wow, thanks a lot, I will admit that I did not understand each and every word up there but I sure have learned a lot :) I will use HashSet as I do not care for order. –  user1804287 Nov 6 '12 at 21:34

Use new HashSet<String> An example:

import java.util.HashSet;
import java.util.Set;

public class MainClass {
  public static void main(String args[]) {
    String[] name1 = { "Amy", "Jose", "Jeremy", "Alice", "Patrick" };

    String[] name2 = { "Alan", "Amy", "Jeremy", "Helen", "Alexi" };

    String[] name3 = { "Adel", "Aaron", "Amy", "James", "Alice" };

    Set<String> letter = new HashSet<String>();

    for (int i = 0; i < name1.length; i++)

    for (int j = 0; j < name2.length; j++)

    for (int k = 0; k < name3.length; k++)

    System.out.println(letter.size() + " letters must be sent to: " + letter);

share|improve this answer
wow, 5 answers in 1 minute. I am loving stackoverflow. Thanks Tim and other peoples. :) –  user1804287 Nov 6 '12 at 21:21

You could just use a HashSet<String> to maintain a collection of unique objects. If the Integer values in your map are important, then you can instead use the containsKey method of maps to test whether your key is already in the map.

share|improve this answer

You may want to use one of the implementing class of java.util.Set<E> Interface e.g. java.util.HashSet<String> collection class.


share|improve this answer

HashSet<String> (or) any Set implementation may does the job for you. Set don't allow duplicates.

Here is javadoc for HashSet.

share|improve this answer

I want to clarify some things here for the original poster which others have alluded to but haven't really explicitly stated. When you say that you want a Unique List, that is the very definition of an Ordered Set. Some other key differences between the Set Interface and the List interface are that List allows you to specify the insert index. So, the question is do you really need the List Interface (i.e. for compatibility with a 3rd party library, etc.), or can you redesign your software to use the Set interface? You also have to consider what you are doing with the interface. Is it important to find elements by their index? How many elements do you expect in your set? If you are going to have many elements, is ordering important?

If you really need a List which just has a unique constraint, there is the Apache Common Utils class org.apache.commons.collections.list.SetUniqueList which will provide you with the List interface and the unique constraint. Mind you, this breaks the List interface though. You will, however, get better performance from this if you need to seek into the list by index. If you can deal with the Set interface, and you have a smaller data set, then LinkedHashSet might be a good way to go. It just depends on the design and intent of your software.

Again, there are certain advantages and disadvantages to each collection. Some fast inserts but slow reads, some have fast reads but slow inserts, etc. It makes sense to spend a fair amount of time with the collections documentation to fully learn about the finer details of each class and interface.

share|improve this answer
This does not provide an answer to the question. To critique or request clarification from an author, leave a comment below their post - you can always comment on your own posts, and once you have sufficient reputation you will be able to comment on any post. –  Zach Saucier Dec 14 '14 at 19:34
It does provide an answer, actually. If he just wants a list that acts like a Set, use org.apache.commons.collections.list.SetUniqueList, but as a programmer, he/we should be more careful than that and should think more about the problem. If this makes my answer better, "How to create a Unique List in Java?" List uniqueList = new SetUniqueList();, that's how.... –  Paul Connolly Dec 14 '14 at 20:29
And Zach, I'm not trying to be a jerk, but did you even read my answer before your comment? Or do you just not understand it? If you don't understand it, that's OK - let me know and I'll expand on the topic. I don't think I should have to write a treatise on data structures in order to give a friendly answer to somebody's question. Nor do I care to go about some meek way of building up my comment reputation when I know the answer and nobody else has really provided it. –  Paul Connolly Dec 14 '14 at 20:48
And by the way, I was neither critiquing or requesting clarification from the author, I was just saying that he can either A) quickly use the class I gave him, or B) take the time to really understand the differences between these classes and relate them to his needs. B obviously takes longer, but will result in better code in the long term. –  Paul Connolly Dec 14 '14 at 20:54

Your Answer

