English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

Java Basic Tutorial

Java flow control

Java Array

Java Object-Oriented (I)

Java Object-Oriented (II)

Java Object-Oriented (III)

Java Exception Handling

Java List (List)

Java Queue (queue)

Java Map collection

Java Set collection

Java Input/Output (I/O)

Java Reader/Writer

Java other topics

Java Set Interface

In this tutorial, we will learn about the Set interface and its methods in Java.

The Set interface of the Java Collections framework provides the functionality of mathematical collections in Java. It inherits the Collection interface.

Unlike the List interface, the Set collection cannot contain duplicate elements.

Classes implementing Set

Since Set is an interface, it is not possible to create an object from it.

To use the features of the Set interface, we can use the following classes:

These classes are defined and implemented in the Collections framework and implement the Set interface.

Interfaces inheriting Set

This Set interface also extends these subinterfaces:

How to use Set?

In Java, you must import the java.util.Set package to use the Set.

//Implement Set using HashSet
Set<String> animals = new HashSet<>();

Here, we create a Set called animals. We have used the HashSet class to implement the Set interface.

Set methods

The Set interface includes all methods of the Collection interface. This is because Collection is the superinterface of Set.

The Set interface also provides some commonly used methods of the Collection interface:

  • add() - Add the specified element to the set

  • addAll() - Add all elements of the specified set to the set

  • iterator() -Return an iterator that can be used to sequentially access the elements of the set

  • remove() - Remove the specified element from the set

  • removeAll() - Remove all elements from the collection that exist in another specified collection

  • keepAll()  -Keep all elements that still exist in another specified collection

  • clear() - Remove all elements from the collection

  • size() - Returns the length of the collection (number of elements)

  • toArray() - Returns an array containing all elements of the collection

  • contains() -  Returns true if the collection contains the specified element

  • containsAll() - Returns true if the collection contains all elements of the specified collection

  • hashCode() -Return the hash code value (the address of the elements in the collection)

Set collection operations

The Java Set interface allows us to perform basic mathematical set operations, such as union, intersection, and subset.

  • Union - To get the union of two collections x and y, we can use x.addAll(y)

  • Intersection - To get the intersection of two collections x and y, we can use x.retainAll(y)

  • Subset - To check if x is a subset of y, we can use y.containsAll(x)

Implementation of the Set interface

1.implement HashSet class

import java.util.Set;
import java.util.HashSet;
class Main {
    public static void main(String[] args) {
        //Create a collection using HashSet class
        Set<Integer> set1 = new HashSet<>();
        //Add elements to set1
        set1.add(2);
        set1.add(3);
        System.out.println("Set1: " + set1);
        //Create another collection using HashSet class
        Set<Integer> set2 = new HashSet<>();
        //Add element
        set2.add(1);
        set2.add(2);
        System.out.println("Set2: " + set2);
        //The union of two collections
        set2.addAll(set1);
        System.out.println("The union is: " + set2);
    }
}

Output Result

Set1: [2, 3]
Set2: [1, 2]
The union is: [1, 2, 3]

For more information about HashSet, please visitJava HashSet.

2.implement TreeSet class

import java.util.Set;
import java.util.TreeSet;
import java.util.Iterator;
class Main {
    public static void main(String[] args) {
        //Create a collection using TreeSet class
        Set<Integer> numbers = new TreeSet<>();
        // Add elements to the set collection
        numbers.add(2);
        numbers.add(3);
        numbers.add(1);
        System.out.println("TreeSet: " + numbers);
        //Access elements using iterator()
        System.out.print("Access elements using iterator(): ");
        Iterator<Integer> iterate = numbers.iterator();
        while(iterate.hasNext()) {
            System.out.print(iterate.next());
            System.out.print(", ");
        }
    }
}

Output Result

TreeSet: [1, 2, 3]
Access elements using iterator(): 1, 2, 3,

For more information on TreeSet, please visitJava TreeSet.

Now that we know what a Set is, in the next tutorial, we will see its implementation in classes such as EnumSet, HashSet, LinkedHashSet, and TreeSet.