Java Set Part I

Java  Set is a type of collection that does not allow duplicate elements. That means an element can only exist once in a Set. It models the set abstraction in mathematics.

This picture illustrates six spoon sets of different color with the same shape  in mathematics:


In set

  • Duplicate elements are not allowed.
  • Elements are not stored in order. That means you cannot expect elements sorted in any order when iterating over elements of a Set.

Based on the characteristics, consider using a Set collection when:

  • You want to store elements distinctly without duplication, or unique elements.
  • You don’t care about the order of elements.

For example, you can use a Set to store unique integer numbers; you can use a Set to store cards randomly in a card game; you can use a Set to store numbers in random order, etc.


    Creating a new Set

Always use generics to declare a Set of specific type, e.g. a Set of integer numbers:

Set<Integer> numbers = new HashSet<>();

Remember using the interface type (Set) on as the reference type, and concrete implementation (HashSet, LinkedHashSet, TreeSet, etc) as the actual object type:

Set<String> names = new LinkedHashSet<>();

We can create a Set from an existing collection. This is a trick to remove duplicate elements in non-Set collection. Consider the following code snippet:

List<Integer> listNumbers = Arrays.asList(3, 9, 1, 4, 7, 2, 5, 3, 8, 9, 1, 3, 8, 6);
Set<Integer> uniqueNumbers = new HashSet<>(listNumbers);


[3, 9, 1, 4, 7, 2, 5, 3, 8, 9, 1, 3, 8, 6]
[1, 2, 3, 4, 5, 6, 7, 8, 9]

You see, the list listNumbers contains duplicate numbers, and the set uniqueNumbers removes the duplicate ones.As with Java 8, we can use stream with filter and collection functions to return a Set from a collection. The following code collects only odd numbers to a Set from the listNumbers above:

Set<Integer> uniqueOddNumbers =
    .filter(number -> number % 2 != 0).collect(Collectors.toSet());


[1, 3, 5, 7, 9]

Note that the default, initial capacity of a HashSet and LinkedHashSet is 16, so if you are sure that your Set contains more than 16 elements, it’s better to specify a capacity in the constructor. For example:

Set<String> bigNames = new HashSet<>(1000);

This creates a new HashSet with initial capacity is 1000 elements.


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Blog at

Up ↑

%d bloggers like this: