Set in Java is an interface declared in java.util package. It extends the collection interface that allows creating an unordered collection or list, where duplicate values are not allowed. As the name implies, a set in Java is used to create a mathematical set. Since the set extends the collection interface, it does not allow duplicate elements. In the hierarchy, NavigableSet and SortedSet are the two interfaces that extend set in Java.

You cannot directly use the set to create its object as it is an interface. Hence, you have to use the four classes, namely EnumSet, HashSet, LinkedHashSet, and TreeSet, that implement the set interface to work with it. Here, you will look at an example to create a set in Java using the HashSet class.

HashSetclass

HashSetclass_Result

As you can see in the above example, the set will not accept duplicate values. Hence, it adds and prints Java only once in set_Name.

Learn the Ins & Outs of Software Development

Caltech Coding BootcampExplore Program
Learn the Ins & Outs of Software Development

What Are the Operations You Can Perform on Set in Java?

A set in Java represents a mathematical set, wherein you can perform various operations such as union, intersection, and difference. You can do this with the help of addAll(), retainAll(), and removeAll() methods for the above three operations, respectively. You will learn about the methods of the set in-detail later in this post. But for now, look at what these operations do and how to perform them on the set. To understand this better, consider two sets, where set1 = [3, 5, 9, 17, 23, 41] and set2 = [2, 5, 13, 17, 41, 51]. With these sets, you can perform the following operations.

  • Union: This operation will return the union of both set1 and set2 after eliminating duplicate values. Hence, the result of the union of set1 and set2 will be [2, 3, 5, 9, 13, 17, 23, 41, 51].
  • Intersection: The intersection will only return the values that are common in both sets. The result of intersecting set1 and set2 will be [5, 17, 41].
  • Difference: This operation will delete the first operand set values that are common with the second operation set. For instance, if you find the difference of set1 from set2, it will be [3, 9, 23]. On the other hand, if you find the difference of set2 from set1, it will be [2, 13, 51].

Observe the example below with the same sets and see if the output matches the results or not.

OperationsonSetsinJava.

OperationsonSetsinJava_result

As you can see, it has created two integer arrays and two sets in the example above. You have then added the array values to the sets. After adding the values in both sets respectively, you performed all three operations by creating a result set for each operation. The answers you got from the code are precisely similar to the ones you calculated mathematically.

Learn more about Java in detail and become job-ready for your software development career with our Caltech Coding Bootcamp.

Learn the Ins & Outs of Software Development

Caltech Coding BootcampExplore Program
Learn the Ins & Outs of Software Development

What Are the Different Set Methods Available?

Set in Java provides a vast array of methods. You can use these methods to perform various operations on the set. The table below lists all the set interface methods along with the description of what operations they perform.

Method

Description

add(element)

Adds a new value to the set

addAll(collection)

Adds all the elements of a collection to the specified set

clear()

Clears all the values of a set (does not clear the set itself)

contains(element)

Checks if the specified element is present in a set

containsAll(collection)

Checks if all the values of a collection are present in a set

hashCode()

Returns an integer hash code for the instance of a set

isEmpty()

Checks if the set is empty

iterator()

Returns an iterator object to parse through the set

remove(element)

Removes a specified value from the set

removeAll(collection)

Removes the elements of a collection from the set to find the difference

retainAll(collection)

Retains the values of a collection in a set

size()

Returns the size of the set

toArray()

Creates an array with the elements of a set

Examples to Use Methods of Set in Java

Since you now know all the set interface methods, let’s use them one-by-one to perform different operations on the set. Here, you must use HashSet and LinkedHashSet classes to create the set objects. However, you can also try with the other two classes: EnumSet and TreeSet.

Example 1: The add() Method

In this example, you must create a Set object and use the add() method to add elements.

SetinJavaEx1

SetinJavaEx1_rslt

Example 2: The addAll() Method

In this example, you must create a set and an array. You should then use the addAll() method to add the array elements, i.e., a collection, to the set.

SetinJavaEx2

SetinJavaEx2_rslt

Example 3: The clear() Method

You must create a set object, add a few elements to it, and then cleared it with the clear() method in the following example.

SetinJavaEx3

SetinJavaEx3_rslt

Example 4: The contains() Method

After creating a set in Java and adding elements to it, you must use the contains() method to check if the specified element is present in the set or not.

SetinJavaEx4

SetinJavaEx4_rslt

Example 5: The containsAll() Method

In this example, you must create three sets. Then you should use the containsAll() method to check if all the elements from the second and third set are present in the first one.

SetinJavaEx5

SetinJavaEx5_rslt

Example 6: The hashCode() Method

Here, create a set and find the hash code of the current instance using the hashCode() method in the following example.

SetinJavaEx6.

SetinJavaEx6_rslt

Example 7: The isEmpty() Method

In the example below, you must create two sets and use the isEmpty() method to find which one is empty.

SetinJavaEx7

SetinJavaEx7_rslt

Example 8: The iterator() Method

For this example, you should create a set in Java, and use the iterator() method to traverse through it, and print all the set elements one-by-one.

SetinJavaEx8

SetinJavaEx8_rslt

Example 9: The remove() Method

Here, you must create a set and then remove some elements using the remove() method in the below example.

SetinJavaEx9

SetinJavaEx9_reslt

Example 10: The removeAll() Method

In this example, you must create an array and a set. You will then use the removeAll() method to remove all the array elements present in the set.

SetinJavaEx10

SetinJavaEx10_rslt.

Learn 15+ In-Demand Tools and Skills!

Automation Testing Masters ProgramExplore Program
Learn 15+ In-Demand Tools and Skills!

Example 11: The retainAll() Method

In the example below, create an array and a set. You will then have to use the retainAll() method to retain the array elements in the set.

SetinJavaEx11

SetinJavaEx11_rslt

Example 12: The size() Method

You must create a set in Java and then use the size() method to find the set’s total size in the following example.

SetinJavaEx12

SetinJavaEx12_rslt

Example 13: The toArray() Method

In the following example, you must create a set and use the toArray() method to create an array of the same elements.

SetinJavaEx13

SetinJavaEx13_rslt

Unleash a High-paying Automation Testing Job!

Automation Testing Masters ProgramExplore Program
Unleash a High-paying Automation Testing Job!

Conclusion

With this, you have reached the end of this article titled ‘Set in Java’. If you wish to further your knowledge in Java and take it up as a career, certification is highly recommended. Learn more about sets in Java and other advanced concepts by applying to Simplilearn’s Online Java Certification Course and excel in Java software development.

Do you have any questions for us? Leave them in the comments section of this article. Our experts will get back to you on the same, soon.

Happy learning!

Our Software Development Courses Duration And Fees

Software Development Course typically range from a few weeks to several months, with fees varying based on program and institution.

Program NameDurationFees
Caltech Coding Bootcamp

Cohort Starts: 24 Feb, 2025

6 Months$ 8,000
Automation Test Engineer Masters Program

Cohort Starts: 8 Jan, 2025

8 months$ 1,499
Full Stack Java Developer Masters Program

Cohort Starts: 8 Jan, 2025

7 months$ 1,449
Full Stack (MERN Stack) Developer Masters Program

Cohort Starts: 8 Jan, 2025

6 Months$ 1,449