Collections Framework - The Set Interface

Set interface Overview

  • Set contains only unique elements. It does not allow duplicates.
  • Set can contain only one null element.
  • Random access of elements is not possible because it don't have get() API.
  • Set also adds a stronger contract on the behavior of equals and hashCode operations, allowing Set instances to be compared meaningfully even if their implementation types differ. Two Set instances are equal if they contain the same elements.
  • As implied by its name, this interface models the mathematical set abstraction.
  • Set does not guarantee an insertion order.

Set Interface Hierarchy Diagram


Set Interface APIs/Methods

  • boolean add(E e) - Adds the specified element to this set if it is not already present (optional operation).
  • boolean addAll(Collection<? extends E> c) - Adds all of the elements in the specified collection to this set if they're not already present (optional operation).
  • _void clear() _- Removes all of the elements from this set (optional operation).
  • boolean contains(Object o) - Returns true if this set contains the specified element.
  • boolean containsAll(Collection<?> c) - Returns true if this set contains all of the elements of the specified collection.
  • boolean equals(Object o) - Compares the specified object with this set for equality.
  • int hashCode() - Returns the hash code value for this set.
  • boolean isEmpty() - Returns true if this set contains no elements.
  • Iterator iterator() - Returns an iterator over the elements in this set.
  • boolean remove(Object o) - Removes the specified element from this set if it is present (optional operation).
  • boolean removeAll(Collection<?> c) - Removes from this set all of its elements that are contained in the specified collection (optional operation).
  • boolean retainAll(Collection<?> c) - Retains only the elements in this set that are contained in the specified collection (optional operation).
  • int size() - Returns the number of elements in this set (its cardinality).
  • default Spliterator spliterator() - Creates a Spliterator over the elements in this set.
  • _Object[] toArray() _- Returns an array containing all of the elements in this set.
  • T[] toArray(T[] a) - Returns an array containing all of the elements in this set; the runtime type of the returned array is that of the specified array.
Let's create simple example Set interface using HashSet implementation class.

Set Interface Simple Example

import java.util.HashSet;

import java.util.Set;

public class CreateHashSetExample {
    public static void main(String[] args) {
        // Creating a HashSet
     Set<String> daysOfWeek = new HashSet<>();

        // Adding new elements to the HashSet
        daysOfWeek.add("Monday");
        daysOfWeek.add("Tuesday");
        daysOfWeek.add("Wednesday");
        daysOfWeek.add("Thursday");
        daysOfWeek.add("Friday");
        daysOfWeek.add("Saturday");
        daysOfWeek.add("Sunday");

        // Adding duplicate elements will be ignored
        daysOfWeek.add("Monday");
        System.out.println(daysOfWeek);
    }
}
Output:
[Monday, Thursday, Friday, Sunday, Wednesday, Tuesday, Saturday]

Set Interface Implementations

The Java platform contains three general-purpose Set implementations: HashSetTreeSet, and LinkedHashSet.
  • HashSet, which stores its elements in a hash table, is the best-performing implementation; however it makes no guarantees concerning the order of iteration.
  • TreeSet, which stores its elements in a red-black tree, orders its elements based on their values; it is substantially slower than HashSet.
  • LinkedHashSet, which is implemented as a hash table with a linked list running through it, orders its elements based on the order in which they were inserted into the set (insertion-order).
Let's demonstrate Set interface API with all these three implementations. There is a separate post for each Set Interface implementations.

HashSet Implementation Class

In this implementation, we will learn Set Interface APIs using HashSet Implementation Class.
  1. Set interface Overview
  2. HashSet class Overview
  3. Create a HashSet and Adding new Elements Example
  • add() method
  • addAll() method
  • HashSet remove API's with Example
  • remove(Object o)
  • removeAll(Collection<?> c)
  • removeIf(Predicate<? super Integer> filter)
  • clear()
  1. Demonstration of How the Set contains duplicates and null values?
  2. HashSet Bulk Operations API's with Examples
  • addAll()
  • retainAll()
  • containsAll()
  • removeAll()
  1. Iterating over a HashSet
  • iterator()
  • Advance for() loop
  • forEachRemaining()
  • forEach()
  1. HashSet with User-defined objects
  2. How to make HashSet thread safe?
Learn HashSet on Guide to HashSet Class

LinkedHashSet Implementation Class

In this implementation, we will learn Set Interface APIs with examples using LinkedHashSet Implementation Class.
  1. Overview of LinkedHashSet class
  2. Create a LinkedHashSet Example
  3. LinkedHashSet Insertion Order Example
  4. LinkedHashSet remove API's with Example
  5. Iterating over a LinkedHashSet
  6. LinkedHashSet with User-defined objects
  7. How to make LinkedHashSet thread safe?
Learn LinkedHashSet on Guide to LinkedHashSet Class

TreeSet Implementation Class

In this implementation, we will learn Set Interface APIs with examples using TreeSet Implementation Class.
  1. Overview of TreeSet Class
  2. Create a TreeSet Example
  3. TreeSet with a custom comparator (Case Insensitive Order)
  4. TreeSet with a custom Comparator Example(Descending order)
  5. Accessing the elements of a TreeSet
  6. Removing elements from a TreeSet
Learn TreeSet on Guide to TreeSet Class
Learn Java Collections Framework on Java Collections Tutorial

Comments