Core Java

Java Set Example (with video)

In this example, we will demonstrate the use of the Java Set interface, which is a part of the Java Collections Framework. It extends the interface Collection, so that all the elements contained have no duplicates and only one null element may appear.

There are several classes implementing the Set interface, such as AbstractSet, EnumSet, HashSet, LinkedHashSet, TreeSet and ConcurrentSkipListSet. This article mainly deals with HashSet and TreeSet classes, as they are the most commonly used classes.

HashSet implements the interface using a hash table. It offers high performance for the basic methods such as add, remove, contains and size. However, the ordering of the elements cannot be tracked and possibly it could change at anytime during execution.

TreeSet uses a TreeMap to store the elements, which keeps them sorted by their natural order or by the comparator that we prefer to use.

You can also check this tutorial in the following video:

Java Set Example – Video

1. Java Set UML Diagram

The following Unified Modelling Language (UML) diagram in Fig.1 depicts the hierarchical relationship between different interfaces and classes, which are related to Set Class in Java. All the classes and interfaces mentioned in the diagram belongs to java.util package.

Java Set - Java Set UML Diagram
Fig.1: Java Set UML Diagram

Here, the Set interface extends the Collection interface, which in turn extends the Iterable interface of Java. Both AbstractSet and SortedSet interfaces extends the Set interface. Further, HashSet class implements the AbstractSet interface and the LinkedHashSet class extends the HashSet class. Also, the TreeSet class implements the NavigableSet interface, which in turn extends the SortedSet interface.

2. How to create a Java Set

In this section, we will see different methods to create the HashSet and TreeSet objects, by calling different types of constructors in Java.

First, let us have a look at the HashSet class constructors:

  • HashSet(): It constructs a new, empty set.
  • HashSet(Collection col): It constructs a new set, which contains the elements of the given collection.
  • HashSet(int initialCapacity): It constructs a new, empty set, with the specified initial capacity.
  • HashSet(int initialCapacity, float loadFactor): It constructs a new, empty set, with the specified initial capacity and load factor.

Now, let us have a look at TreeSet class constructors:

  • TreeSet(): It constructs a new, empty set in which the objects will be sorted and stored in the ascending order by default.
  • TreeSet(Comparator comp): It constructs a new, empty set in which the objects are stored based upon the sorting order specified.
  • TreeSet(Collection col): It constructs a new set, which contains the elements of the given Collection.
  • TreeSet(SortedSet s): It constructs a new set, which contains the elements of the given SortedSet.

3. Common Methods

  • add(Object): It adds a new element, if it does not exist already.
  • addAll(Collection): It adds all the elements of the given collection, if they do not exist already. If the given collection is also a set, then the execution of the method results in the union of the two sets.
  • contains(Object): It returns true, if the element/object given exists in the set.
  • containsAll(Collection): It returns true, if all the elements in the given collection exist in the set. In case the given collection is a set, the method return true, if it is a subset of this set.
  • equals(Object): It returns true, if the given object that is compared with this set is also a set, i.e., both of them contain the same number of elements and every element of the given set is contained in this set.
  • size(): It returns the number of elements in the set.
  • remove(Object): It removes the specified elements from the set.
  • removeAll(Collection): It removes all the elements from the set that the collection contains.
  • clear(): It removes all the elements from the set, resulting in an empty set.
  • isEmpty(): It returns true, if the set has no elements.
  • hashCode(): It returns the hash code value of this set. The hash code of a set is the sum of the hash codes of the elements contained in the set.
  • toArray(): It returns an array containing all the elements of this set.

4. Comparison of Set Classes

In this section we compare the major 2 Set interface implementations, viz., HashSet and TreeSet classes, based upon their usage, complexities and various other factors.

S.No. HashSet TreeSet
1. HashSet implements the Set interface by Hash tables. TreeSet implements the Set interface by Tree structure (generally Red Black trees).
2. HashSet is internally backed by HashMap to store the elements. TreeSet is internally backed by TreeMap to store the elements.
3. The elements in the HashSet are not stored in any order. The elements in the TreeSet are stored in ascending order by default and the order can be changed with the help of Comparator or Comparable method.
4. The performance of HashSet is better than TreeSet, if order is not needed. The performance of TreeSet is worse than HashSet.
5. The time complexity of insertion, deletion and searching operation is constant, i.e., O(1). The time complexity of insertion, deletion and searching operation is O(log(n)).
6. HashSet uses less memory space, as it only uses HashMap to store the elements of the set internally. TreeSet uses more memory space, as it stores comparator to sort the elements along with the elements in the TreeMap.
7. HashSet is always preferred when there is no compulsion to store the elements in the sorted manner. TreeSet is generally preferred only when the elements must be stored in the sorted manner.
8. Null objects can be stored within the HashSet. Null objects cannot be stored within the TreeSet, as compareTo() method will throw java.lang.NullPointerException when called with TreeSet object containing Null.
9. HashSet can store heterogeneous objects within it. TreeSet cannot store heterogeneous objects within it, as it throws ClassCastException when attempted to store heterogeneous objects.
10. HashSet uses equals() or hashcode() method to compare two objects of the set or to identify the duplicate values. TreeSet uses compare() or compareTo() method to compare two objects of the set or to identify the duplicate values.
11. HashSet does not provide much functionality, therefore making it little difficult to use when compared to TreeSet. TreeSet provides greater functionality when compared to HashSet. TreeSet provides functions like first(), last(), pollFirst(), pollLast(), floor(), ceiling(), etc. which makes it easier to use when compared to HashSet.
12. The performance of the HashSet can be altered with the help of initialCapacity and loadFactor. The TreeSet do not have any such mechanism to alter its performance.

5. Examples of using Set in Java

This section provides the detailed implementation of using Set, mainly HashSet and TreeSet with the examples.

5.1 Enum Set Example

EnumSet is an implementation of the Set interface. It extends the Abstract Set class. It implements Set Interface. It is not a synchronized Java Collection. It is more performant than HashSet. EnumSet has elements from the single enumeration type. The type is specified when the set is created explicitly or implicitly. It does not allow null-type objects. EnumSet throws NullpointerException when a null object is added. EnumSet has a fail-safe iterator and it can handle modification of the collection while iterating. We can see the example code and the output when the code is executed.

EnumSetExample.java

package com.javacodegeeks.core.set;

import java.util.EnumSet;


enum Activities { PLAY, LEARN, CONTRIBUTE, QUIZ, SCRABBLE };


public class EnumSetExample {


	public static void main(String[] args) {


		EnumSet set1, set2, set3, set4;


		set1 = EnumSet.of(Activities.QUIZ, Activities.CONTRIBUTE,
						Activities.LEARN, Activities.PLAY);
		set2 = EnumSet.complementOf(set1);
		set3 = EnumSet.allOf(Activities.class);
		set4 = EnumSet.range(Activities.PLAY, Activities.CONTRIBUTE);


		System.out.println("Set 1: " + set1);
		System.out.println("Set 2: " + set2);
		System.out.println("Set 3: " + set3);
		System.out.println("Set 4: " + set4);
	}
}


Execution of EnumSetExample class

(base) apples-MacBook-Air:setExample bhagvan.kommadi$ java -cp src com.javacodegeeks.core.set.EnumSetExample
Set 1: [PLAY, LEARN, CONTRIBUTE, QUIZ]
Set 2: [SCRABBLE]
Set 3: [PLAY, LEARN, CONTRIBUTE, QUIZ, SCRABBLE]
Set 4: [PLAY, LEARN, CONTRIBUTE]

5.2 HashSet Example

Let us see how we can use HashSet in practice:

HashSetExample.java

//Java Program to demonstrate the usage of HashSet
package com.javacodegeeks.core.set;

import java.util.*;

public class HashSetExample {

    public static void main(String args[]) {

        // We create a new, empty set
        Set<String> mySet1 = new HashSet<String>();
        // We add a few elements
        mySet1.add("A");
        mySet1.add("C");
        mySet1.add("A");
        mySet1.add("B");
        // Print the elements of the Set
        System.out.println("mySet1: " + mySet1);

        // Create a list and add some elements
        List<String> list = new ArrayList<String>();
        list.add("A");
        list.add("C");
        list.add("A");
        list.add("A");
        list.add("B");
        list.add("C");
        // Now create the set using the appropriate constructor
        Set<String> mySet2 = new HashSet<String>(list);
        // Print the elements of the list an the the set
        System.out.println("list: " + list);
        System.out.println("mySet2: " + mySet2);

        // Compare the two sets
        System.out.println("MySet1 matches mySet2: " + mySet1.equals(mySet2));

        // Now we will remove one element from mySet2 and compare again
        mySet2.remove("A");
        System.out.println("mySet2: " + mySet2);
        System.out.println("MySet1 matches mySet2: " + mySet1.equals(mySet2));

        // Lets check if our sets contain all the elements of the list
        System.out.println("MySet1 contains all the elements: " + mySet1.containsAll(list));
        System.out.println("MySet2 contains all the elements: " + mySet2.containsAll(list));

        // Use of Iterator in Set
        Iterator<String> iterator = mySet1.iterator();
        while (iterator.hasNext()) {
            System.out.println("Iterator loop: " + iterator.next());
        }

        // Use of for-each in Set
        for (String str : mySet1) {
            System.out.println("for-each loop: " + str);
        }

        // Clearing all the elements
        mySet1.clear();
        System.out.println("mySet1 is Empty: " + mySet1.isEmpty());

        // Checking the number of elements
        System.out.println("mySet1 has: " + mySet1.size() + " Elements");
        System.out.println("mySet2 has: " + mySet2.size() + " Elements");

        // Creating an Array with the contents of the set
        String[] array = mySet2.toArray(new String[mySet2.size()]);
        System.out.println("The array:" + Arrays.toString(array));
    }
}

Output

mySet1: [A, B, C]
list: [A, C, A, A, B, C]
mySet2: [A, B, C]
MySet1 matches mySet2: true
mySet2: [B, C]
MySet1 matches mySet2: false
MySet1 contains all the elements: true
MySet2 contains all the elements: false
Iterator loop: A
Iterator loop: B
Iterator loop: C
for-each loop: A
for-each loop: B
for-each loop: C
mySet1 is Empty: true
mySet1 has: 0 Elements
mySet2 has: 2 Elements
The array:[B, C]

5.3 LinkedHashSet Example

LinkedHashSet is an ordered HashSet. It has a double-linked list with elements. LinkedHashSet helps in maintaining the iterator order. The order is not predictable while iterating in a HashSet. LinkedHashSet can be used to iterate through the elements in the order the elements are inserted. Similarly while cycling through LinkedhashSet, the iterator will return the elements in the order of insertion. We can see the example code and the output when the code is executed.

LinkedHashSetExample.java

package com.javacodegeeks.core.set;

import java.util.LinkedHashSet;


public class LinkedHashSetExample {


	public static void main(String[] args)
	{


		LinkedHashSet linkedset
			= new LinkedHashSet();


		linkedset.add("Apple");
		linkedset.add("Bat");
		linkedset.add("Cat");
		linkedset.add("Dog");


		linkedset.add("Apple");
		linkedset.add("Egg");


		System.out.println("Size  = "
						+ linkedset.size());

		System.out.println("Initial LinkedHashSet:"
						+ linkedset);


		System.out.println("Removing Dog: "
						+ linkedset.remove("Dog"));


		System.out.println(
			"Remove Zebra "
			 + linkedset.remove("Zebra"));


		System.out.println("Checking if Apple is there="
						+ linkedset.contains("Apple"));


		System.out.println("Updated: "
						+ linkedset);
	}
}


Execution of LinkedHashSetExample class

(base) apples-MacBook-Air:setExample bhagvan.kommadi$ java -cp src com.javacodegeeks.core.set.LinkedHashSetExample
Size  = 5
Initial LinkedHashSet:[Apple, Bat, Cat, Dog, Egg]
Removing Dog: true
Remove Zebra false
Checking if Apple is there=true
Updated: [Apple, Bat, Cat, Egg]

5.4 TreeSet Example

The following example depicts the usage of TreeSet in Java.

TreeSetExample.java

//Java Program to demonstrate the usage of TreeSet
package com.javacodegeeks.core.set;

import java.util.*;

public class TreeSetExample {
  public static void main(String args[]) {
    //Creating a new empty TreeSet object
    TreeSet<String> language = new TreeSet<String>();

    //Inserting the elements in the set using add() method
    language.add("Python");
    language.add("Java");
    language.add("Ruby");
    language.add("C++");
    language.add("Java");

    //Elements are displayed in the sorted manner, as they are by default stored in ascending order within TreeSet. Also, the duplicate values are stored only once in the Set.
    System.out.println("The Languages entered in TreeSet: ", language);

    //Printing the size of the TreeSet object
    System.out.println("Number of elements in \'language\' object is ", language.size());

    //Checking if an element exists in the TreeSet object or not, with contains() method
    System.out.println("Does \'Ruby\' exist in \'language\': ", language.contains("Ruby"));
    System.out.println("Does \'PHP\' exist in \'language\': ", language.contains("PHP"));

    //Remove an element from the TreeSet object
    language.remove("Python");
    System.out.println("Languages after removing Python from TreeSet: ", language);
  }
}

Output

The Languages entered in TreeSet: [C++, Java, Python, Ruby]
Number of elements in language object is 4
Does Ruby exist in language: true
Does PHP exist in language: false
Languages after removing Python from TreeSet: [C++, Java, Ruby]

7. Download the Source Code

This was a Java Set Example.

Download
Download the Eclipse project of this example: Java Set Example

Last updated on October 19th, 2022

Dhruvi Goyal

Dhruvi Goyal is a graduate and University Gold Medalist in Bachelor of Computer Application from GGS Indraprastha University. She is currently pursuing M.Sc. Applied Operational Research from University of Delhi. She is a coder and a data science enthusiast. She has undertaken various projects and research work in the field of Computer Science, Data Science and Optimization. She is co-author of a book entitled "Data Structure Using C" and has published research papers in reputed International Journals and Conferences. She was also a member of Software Development Cell at Maharaja Surajmal Institute.
Subscribe
Notify of
guest

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

0 Comments
Inline Feedbacks
View all comments
Back to top button