Java Set: The Complete Guide

Set has various methods to add, remove clear, size, etc., to enhance the usage of an interface. Set also adds the stronger contract on a behavior of the equals and hashCode operations, allowing the Set instances to be compared meaningfully even if their implementation types differ.

Java Set

Java Set is a collection of objects that contains no duplicate values. The following are the key features of a set. First, the Set is the interface that extends Collection. It is the unordered collection of objects in which duplicate values cannot be stored. Set is implemented by the HashSet, LinkedHashSet, or TreeSet (sorted representation). 

Features of Set in Java

A Set is an interface that extends the Collection interface. An Interface is the Collection of abstract methods. A class in java implements the interface to inherit and define these abstract methods of the interface.)

The Set contains all unique values. I.e., The duplicate values cannot be stored in the Set. Therefore, if you try to add any value into the Set already present in it, it will simply skip adding those values again and retain only one unique element as every element. 

The Set interface is implemented by the following classes: HashSet, TreeSet, etc. 

This means that the HashSet class, the TreeSet class (and all the other capable classes) implement the interface Set and inherit its abstract members, and now they can define these members in their bodies. These classes can implement the set properties and the collection properties through this. 

When the HashSet Class implements the Set, then we get our values in an unordered manner because the HashSet stores the values in the hashtable. While displaying the value, it shows the values according to the locations (nearest) in which they are stored.

See the code example.

import java.sql.SQLOutput;
import java.util.HashSet;
import java.util.Set;

public class Set_Demo1 {
    public static void main(String[] args) {
        Set<String> fruits = new HashSet<String>();

        fruits.add("Apple");
        fruits.add("Banana");
        fruits.add("Orange");
        fruits.add("Grapes");
        fruits.add("Kiwi");

        System.out.println(fruits);

    }
}

See the output.

Features of Set

Here, you can see that the fruits displayed on the output are neither in the order in which they were entered nor in ascending or descending order (according to lexical order).

If the TreeSet is implementing the Set, you get the output in ascending order because, in the Background of the TreeSet class, it follows such an algorithm that sorts the values in ascending order while storing them? See the following code.

import java.util.Set;
import java.util.TreeSet;

public class Set_Demo2 {
    public static void main(String[] args) {
        Set<String> fruits = new TreeSet<String>();

        fruits.add("Apple");
        fruits.add("Banana");
        fruits.add("Orange");
        fruits.add("Grapes");
        fruits.add("Kiwi");

        System.out.println(fruits);

    }
}

See the output.

Features of Set

Here, you can see that the fruits displayed in the output are in ascending order according to their first letters.

A set follows all the properties of collections, but it also has some surplus features, which makes it unique. The following are the key features that make a set different from other Collections.

  1. No duplicate elements.
  2. The mathematical sets can be well implemented using The Java Set. Operations like Set Union, Set6 Intersection and Set Difference can easily be performed using readymade methods, i.e. addAll() , retainAll() and removeAll(). 

The other properties remain the same as all the rest of the Collections, such as the Lists.

import java.util.Set;
import java.util.TreeSet;

public class SetDemo {
    public static void main(String[] args) {

        Set<Integer> setA = new TreeSet<Integer>();
        Set<Integer> setB = new TreeSet<Integer>();

        for (int i = 0; i < 20; i += 2)
            setA.add(i); // Numbers divisible by 2

        for (int i = 0; i < 20; i += 3)
            setB.add(i); // Numbers divisible by 3

        // Union of setA and setB
        Set<Integer> A_union_B = new TreeSet<>(setA);
        A_union_B.addAll(setB);
        System.out.println("Numbers Divisible by either 2 or 3 or both are: " + A_union_B);

        // Intersection of setA and setB
        Set<Integer> A_intersects_B = new TreeSet<>(setA);
        A_intersects_B.retainAll(setB);
        System.out.println("Numbers Divisible by both 2 and 3 are: " + A_intersects_B);

        // Difference of setA and setB
        Set<Integer> A_minus_B = new TreeSet<>(setA);
        A_minus_B.removeAll(setB);
        System.out.println("Numbers Divisible by 2 but not 3 are: " + A_minus_B);

        Set<Integer> B_minus_A = new TreeSet<>(setB);
        B_minus_A.removeAll(setA);
        System.out.println("Numbers Divisible by 3 but not 2 are: " + B_minus_A);
    }
}

See the output.

Set Example In Java Tutorial

Java Set Methods

Sr.No. Method & Description
1 add( )

It adds an object to the Collection.

2 clear( )

It removes all objects from the Collection.

3 contains( )

It returns true if a specified object is an element within the Collection.

4 isEmpty( )

It returns true if the Collection has no elements.

5 iterator( )

It returns the Iterator object for a collection, which may be used to retrieve the object.

6 remove( )

It removes the specified object from a collection.

7 size( )

It returns several elements to the Collection.

That’s it for this tutorial.

Recommended Posts

Thread Pools In Java

Java List Interface

Java Merge Sort

Insertion Sort In Java

For-each Loop In Java

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.