Introduction to Java Collections Set Interface

This is a complete Introduction to Java Set collections interface. You will learn details of Set interface, main characteristics and also how the Set is different than other collections of Java.

Introduction to Set

Set is one of the collections Interface in Java which resides in java.util package. However, Set extends Collection interface.

The Collection is a root interface of Java Collections hierarchy. Also, the Collections extends Iterable that provides methods with an ability to iterate collection.

A set is defined as a collection unique elements. Set doesn’t map elements to any specific indexes. Neither it has a key, value pair. Moreover, when you add an element to a Set, you don’t have any way of accessing that element directly. All you can do is, check if that element exists or remove that element. Additionally, you can create an iterator over the set and iterate through each element, until you find desired element or you reached till the last element.

In the next sections, we will look into various methods provided by the Set interface.

Immutable Sets

  • You cannot add, remove elements from it. Otherwise you get UnsupportedOperationException.
  • Null elements are not allowed at all.
  • If all the elements are Serializable, the Set is Serializable.
  • If elements are injected at creation time, it throws IllegalArgumentException.

Static Factory Methods (Java 9)

The Java 9 release brought static factory methods in the Set interface. These are static default methods.

Set<String> stringSet = Set.of("Bread", "Milk", "Eggs", "Cheese", "Butter");

Set<Long> longSet = Set.of(123L, 12L);Code language: Java (java)

Using the static factory method, you can create set of any data type by just passing the elements. However, the resulted set is Immutable, which means you can’t modify the set after it is created.

//Returns an immutable set containing zero elements.
static <E> Set<E> of​();

//Returns an immutable set containing one element.
static <E> Set<E> of​(E e1);

//Returns an immutable set containing an arbitrary number of elements.
static <E> Set<E> of​(E... elements);	

//Returns an immutable set containing two elements.
static <E> Set<E> of​(E e1, E e2);	

//Returns an immutable set containing three elements.
static <E> Set<E> of​(E e1, E e2, E e3);	

//Returns an immutable set containing four elements.
static <E> Set<E> of​(E e1, E e2, E e3, E e4);	

//Returns an immutable set containing five elements.
static <E> Set<E> of​(E e1, E e2, E e3, E e4, E e5);	

//Returns an immutable set containing six elements.
static <E> Set<E> of​(E e1, E e2, E e3, E e4, E e5, E e6);	

//Returns an immutable set containing seven elements.
static <E> Set<E> of​(E e1, E e2, E e3, E e4, E e5, E e6, E e7);	

//Returns an immutable set containing eight elements.
static <E> Set<E> of​(E e1, E e2, E e3, E e4, E e5, E e6, E e7, E e8);	

//Returns an immutable set containing nine elements.
static <E> Set<E> of​(E e1, E e2, E e3, E e4, E e5, E e6, E e7, E e8, E e9);	

//Returns an immutable set containing ten elements.
static <E> Set<E> of​(E e1, E e2, E e3, E e4, E e5, E e6, E e7, E e8, E e9, E e10);	
Code language: Java (java)

Add Elements to Set

Below are the methods to add elements to an existing Set.

  • boolean add​(E e): Adds given element to existing Set. However, the Set does equality check before putting the element. If an equal element already present, this method returns false and does nothing.
  • boolean addAll(Collection<? extends E> c): This method takes a collection. Checks if the the elements are unique and are not already present in the Set. Returns false if duplicate element is found.
List<Integer> lists = Arrays.asList(1, 2, 3, 4, 5);

Set<Integer> set = new HashSet<>();
set.addAll(lists);
set.forEach(System.out::print);

// Output
// 12345Code language: Java (java)

Querying the existing Sets

Also, Java has provided, couple of methods using which you can query state of existing Set.

  • boolean contains(Object o): You can pass an object to know if the set already contains it inside.
  • boolean containsAll(Collection<?> c): Similar to contains method. However, it takes a collection. You can check if the elements of given collection are already part of the set.
  • int size(): Return the total number of elements in the set.
  • boolean isEmpty(): Check if the set is empty.

Remove Elements from Set

Finally, let’s see how to remove elements from a set.

  • boolean remove(Object o): You can remove the given element from the Set if present. Returns true if it is found and removed.
  • boolean removeAll(Collection<?> c): You can pass a collection of elements to be removed from Set.
  • boolean retainAll(Collection<?> c): You can remove all the elements except the ones passed in the collection.

Summary

In this short tutorial we had an overview of Java Set Interface. To sum up, set represent unique dataset and it is an important element in the Java Collections. Also, we saw various methods to add, check, and remove elements from a Set. Additionally, we also learnt Java 9’s Static Default methods to create Immutable Set instances.