What is Java Set?

An infographic explain what is Java Set. It shows main points about sets e.g. implementation classes (Hashset, Treeset), with an example.

Set interface in Java

Set is a Collection in Java like the List interface.

The difference between the two is that the Java Set does not allow duplicate elements.

Just like the List interface, the Set also has implementation classes like HashSet.

Important points about Java Set

  • The Set is a subinterface of Collection.
  • It does not allow duplicate elements.
  • It inherits methods from the Collection.
  • The Set adds a strong contract on the behavior of hashCode and equals operations.
  • The index of Set elements starts at 0.
  • As Set is an interface, its object cannot be initialized.
  • The Set is implemented by HashSet, TreeSet, and LinkedHashSet.
  • The Set interface is part of java.util package.

The following section demonstrates how Set can be used in Java programs.

An example of creating a set with a HashSet class

In this example, a Set is created by using the HashSet class. The HashSet is backed by the hash table that makes no guarantee of the iteration order.

Five integer elements are created by the add method and displayed by using the for..each loop. You can see the difference in the order of adding the elements and as they are displayed:

import java.util.*;

public class set_demo {

    public static void main(String []args) {

                Set<Integer> aSet_demo = new HashSet<Integer> (5);

                aSet_demo.add(5);

                aSet_demo.add(10);

                aSet_demo.add(15);

                aSet_demo.add(20);

                aSet_demo.add(25);

        //Displaying the Set elements
        for (Integer currSetElement : aSet_demo) {
            System.out.println("The Set element: "+currSetElement);
         }

 }

}

Output:

The Set element: 25
The Set element: 10
The Set element: 20
The Set element: 5
The Set element: 15

An example of using the LinkedHashSet for creating a Set

You should use the LinkedHashSet class when iteration in insertion order is required.

As such, the HashSet does not guarantee the iteration order and the order of elements is unpredictable as compared to insertion order. In certain scenarios, you may want the same order as elements are inserted.

See this example where I created a Set by using the LinkedHashSet class. Four string elements are entered by using the add() method and finally the Set is displayed by using the for..each loop:

The code:

import java.util.*;

public class set_demo {

    public static void main(String []args) {

                Set<String> aSet_String = new LinkedHashSet<String> (4);

                aSet_String.add("The");

                aSet_String.add("Set");

                aSet_String.add("With");

                aSet_String.add("LinkedHashSet");

        //Displaying the Set elements
        for (String currSetElement : aSet_String) {
            System.out.println("The Set element: "+currSetElement);
         }

 }

}

Output:

The Set element: The
The Set element: Set
The Set element: With
The Set element: LinkedHashSet

You can see the order of displaying the elements is the same as those that were inserted.

What happens if duplicate elements are added to a Set?

To demonstrate this scenario, I have created a Set with fruit names. A total of six elements are inserted that are fruit names as follows:

fruit_Set.add(“Mango”);

fruit_Set.add(“Banana”);

fruit_Set.add(“Apple”);

fruit_Set.add(“Grapes”);

fruit_Set.add(“Banana”);

fruit_Set.add(“Pine Apple”);

You can see, the Banana is added at 1 and 4 index positions of the Set. Now, have a look at the output for displaying the total number of elements in the set by using the size method and the element values by using a for loop:

The code of Set in Java with duplicate entries:

import java.util.*;

public class set_demo {

    public static void main(String []args) {

                Set<String> fruit_Set = new LinkedHashSet<String>();

                fruit_Set.add("Mango");
                fruit_Set.add("Banana");
                fruit_Set.add("Apple");
                fruit_Set.add("Grapes");
                fruit_Set.add("Banana");
                fruit_Set.add("Pine Apple");

        //Displaying the Set elements

        System.out.println("Total number of elements in the Set: "+fruit_Set.size());            
        System.out.println("\n");

        for (String currSetElement : fruit_Set) {
            System.out.println("The fruit name: "+currSetElement);
         }
 }

}

Result:

Total number of elements in the Set: 5The fruit name: Mango
The fruit name: Banana
The fruit name: Apple
The fruit name: Grapes
The fruit name: Pine Apple

You can see, the size method is only returned 5 as the total number of elements. As using the for loop for displaying Set Java elements, it displayed Banana once i.e. the first occurrence only.

An example of using the clear method of set

The clear method of the Set can be used for removing all elements from the specified Set. See this example where I created a Set with four elements.

The Set is displayed before and after using the clear() method:

The code for clearing the Set objects:

import java.util.*;
public class set_demo {
    public static void main(String []args) {

                Set<String> fruit_Set = new LinkedHashSet<String>();

                fruit_Set.add("Mango");
                fruit_Set.add("Banana");
                fruit_Set.add("Apple");
                fruit_Set.add("Grapes");

        System.out.println("The Set before using clear method:"); 
        System.out.println(fruit_Set);
        System.out.println("\n");

         fruit_Set.clear();
         System.out.println("The Set after using clear method:");
         System.out.println(fruit_Set);
 }

}

Output:

The Set before using clear method:
[Mango, Banana, Apple, Grapes]The Set after using clear method:
[]

Removing a specific element from the Set example

You may also remove only a specific element from the list by using the remove() method. See this example where “Apple” is deleted by using the remove() method:

The code:

import java.util.*;

public class set_demo {

    public static void main(String []args) {
                Set<String> fruit_Set = new LinkedHashSet<String>();

                fruit_Set.add("Mango");
                fruit_Set.add("Banana");
                fruit_Set.add("Apple");
                fruit_Set.add("Grapes");

        System.out.println("The Set before removing object:");      
        System.out.println(fruit_Set);
        System.out.println("\n");

         fruit_Set.remove("Apple");
         System.out.println("The Set after removing object:");
         System.out.println(fruit_Set);

 }
}

Result:

The Set before removing object:
[Mango, Banana, Apple, Grapes]The Set after removing object:
[Mango, Banana, Grapes]

A demo of using an iterator object

In the above examples, we used a “for each loop” to iterate through the Set elements. You may also use the iterator object for going through a Set.

In this example, a set of Java is created by using the LinkedHashSet class. After that, the iterator object is created and a while loop is used as follows:

The code with iterator object:

import java.util.*;

public class set_demo {

    public static void main(String []args) {

                Set<String> a_Set = new LinkedHashSet<String>();

                a_Set.add("Java");
                a_Set.add("Set");
                a_Set.add("Tutorial");

                Iterator<String> set_iterator = a_Set.iterator();
                System.out.println("Displaying Set elements by iterator object:");
                System.out.println("\n");
 
               while(set_iterator.hasNext()){

            System.out.println(set_iterator.next());
        }
 }
}

Output:

Displaying Set elements by iterator object:Java
Set
Tutorial

A demo of using the TreeSet class for creating a Set

In the following example, a Set is created by using the TreeSet class. The Set of color names is created and displayed:

The code with TreeSet:

import java.util.*;

public class set_demo {

    public static void main(String []args) {

                Set<String> a_Set = new TreeSet<String>();

                a_Set.add("Green");
                a_Set.add("Yellow");
                a_Set.add("Red");
                a_Set.add("Orange");
                a_Set.add("Blue");


                Iterator<String> set_iterator = a_Set.iterator();
                System.out.println("The Set with TreeSet class:");
                System.out.println("\n");

                while(set_iterator.hasNext()){
            System.out.println(set_iterator.next());
        }
 }
}

Result:

The Set with TreeSet class:Blue
Green
Orange
Red
Yellow

You can see that an unordered set is created and displayed.

Author - Atiq Zia

Atiq is the writer at jquery-az.com, an online tutorial website started in 2014. With a passion for coding and solutions, I navigate through various languages and frameworks. Follow along as we solve the mysteries of coding together!