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:

kalas-piece-flatware-set-assorted-colors__0145351_PE304800_S4

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:

1
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:

1
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:

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

Output:

1
2
[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:

1
2
3
4
Set<Integer> uniqueOddNumbers = listNumbers.stream()
    .filter(number -> number % 2 != 0).collect(Collectors.toSet());
System.out.println(uniqueOddNumbers);

Output:

1
[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:

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

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

Leave a comment

Create a free website or blog at WordPress.com.

Up ↑