This Java Set Tutorial Explains All about the Set Interface in Java. It covers how to Iterate through a Set, Set Methods, Implementation, Set to List, etc.:
Set in Java is an interface that is a part of the Java Collection Framework and implements the Collection interface. A set collection provides the features of a mathematical set.
A set can be defined as a collection of unordered objects and it cannot contain duplicate values. As the set interface inherits the Collection interface, it implements all the methods of the Collection interface.
=> Check Out The Perfect Java Training Guide Here.
Table of Contents:
Java Set
The set interface is implemented by classes and interfaces as shown in the below diagram.
As shown in the above diagram, Set interface is inherited by classes, HashSet, TreeSet, LinkedHashSet, and EnumSet. The interfaces SortedSet and NavigableSet also implement Set interface.
Some of the important characteristics of the Set interface are given below:
- The set interface is a part of the Java Collections Framework.
- The set interface allows for unique values.
- It can have at most one null value.
- Java 8 provides a default method for the set interface – Spliterator.
- The set interface does not support the indexes of the elements.
- The set interface supports generics.
How To Create A Set?
The set interface in Java is a part of the java.util package. To include a set interface in the program, we have to use one of the following import statements.
import java.util.*;
or
import java.util.Set;
Once set interface functionality is included in the program, we can create a set in Java using any of the set classes (classes that implement set interface) as shown below.
Set<String> colors_Set = new HashSet<>();
We can then initialize this set object by adding a few elements to it using the add method.
colors_Set.add(“Red”); colors_Set.add(“Green”); colors_Set.add(“Blue”);
Set Example In Java
Let’s implement a simple example in Java to demonstrate the Set interface.
import java.util.*; public class Main { public static void main(String[] args) { // Set demo with HashSet Set<String> Colors_Set = new HashSet<String>(); Colors_Set.add("Red"); Colors_Set.add("Green"); Colors_Set.add("Blue"); Colors_Set.add("Cyan"); Colors_Set.add("Magenta"); //print set contents System.out.print("Set contents:"); System.out.println(Colors_Set); // Set demo with TreeSet System.out.print("\nSorted Set after converting to TreeSet:"); Set<String> tree_Set = new TreeSet<String>(Colors_Set); System.out.println(tree_Set); } }
Output:
Set contents:[Red, Cyan, Blue, Magenta, Green]
Sorted Set after converting to TreeSet:[Blue, Cyan, Green, Magenta, Red]
Iterate Through Set In Java
We can access each of the elements of a Set using various approaches. We will discuss these approaches below.
Using Iterator
We can define an iterator to traverse through a set object. Using this iterator we can access each element in the Set and process it.
The following Java program demonstrates iterating through the set and prints the set elements.
import java.util.*; import java.util.HashSet; public class Main { public static void main(String args[]) { // Create a HashSet object and initialize it Set<String> cities_Set = new HashSet<String>(); cities_Set.add("Bangaluru"); cities_Set.add("Pune"); cities_Set.add("Hyderabad"); cities_Set.add("Kolkata"); // Print the set contents System.out.println("HashSet: " + cities_Set); // Create an iterator for the cities_Set Iterator iter = cities_Set.iterator(); // print the set contents using iterator System.out.println("Values using Iterator: "); while (iter.hasNext()) { System.out.print(iter.next()+ " "); } } }
Output:
HashSet: [Bangaluru, Pune, Kolkata, Hyderabad]
Values using Iterator:
Bangaluru Pune Kolkata Hyderabad
Using The For-each Loop
We can also use the for-each loop to access the elements in a set. Here we iterate through the set in a loop.
The following program demonstrates this.
import java.util.*; import java.util.HashSet; public class Main { public static void main(String args[]) { // Create a HashSet object and initialize it Set<String> cities_Set = new HashSet<String>(); cities_Set.add("Bangaluru"); cities_Set.add("Pune"); cities_Set.add("Hyderabad"); cities_Set.add("Kolkata"); // Print the set contents System.out.println("HashSet: " + cities_Set); System.out.println("\nSet contents using forEach loop:"); // print the set contents using forEach loop for(String val : cities_Set) { System.out.print(val + " "); } } }
Output:
HashSet: [Bangaluru, Pune, Kolkata, Hyderabad]
Set contents using forEach loop:
Bangaluru Pune Kolkata Hyderabad
Using Java 8 Stream API
We can also iterate and access set elements using Java 8 stream API. In this, we generate a stream from a set and then iterate through the stream using the forEach loop.
The Java program below demonstrates the iteration of the set using the Java 8 stream API.
import java.util.*; import java.util.HashSet; import java.util.stream.*; public class Main { public static void main(String args[]) { // Create a HashSet object and initialize it Set<String> cities_Set = new HashSet<String>(); cities_Set.add("Bangaluru"); cities_Set.add("Pune"); cities_Set.add("Hyderabad"); cities_Set.add("Kolkata"); // Print the set contents System.out.println("HashSet: " + cities_Set); System.out.println("\nSet contents using Java 8 stream API:"); //generate a stream from set Stream<String> stream = cities_Set.stream(); //iterate the stream using forEach loop to print the elements stream.forEach((element) -> { System.out.print(element + " "); }); } }
Output:
HashSet: [Bangaluru, Pune, Kolkata, Hyderabad]
Set contents using Java 8 stream API:
Bangaluru Pune Kolkata Hyderabad
Set Methods API
Given below are the methods supported by the Set interface. These methods perform basic operations like add, remove, contains, etc. along with the other operations.
Method | Method Prototype | Description |
---|---|---|
add | boolean add ( E e ) | Adds the element e to the set if it is not present in the set |
addAll | boolean addAll ( Collection c ) | Adds the element of the collection c to the set. |
remove | boolean remove ( Object o ) | Deletes the given element o from the set. |
removeAll | boolean removeAll ( Collection c ) | Removes the elements present in the given collection c from the set. |
contains | boolean contains ( Object o ) | Checks if the given element o is present in the set. Returns true if yes. |
containsAll | boolean containsAll ( Collection c ) | Checks if the set contains all the elements in the specified collection; Returns true if yes. |
isEmpty | boolean isEmpty () | Checks if the set is empty |
retainAll | boolean retainAll (Collection c) | Set retains all the elements in the given collection c |
clear | void clear () | Clears the set by deleting all the elements from the set |
iterator | Iterator iterator () | Used to obtain the iterator for the set |
toArray | Object[] toArray () | Converts the set to array representation that contains all the elements in the set. |
size | int size () | Returns the total number of elements or size of the set. |
hashCode | hashCode () | Returns hashCode of the set. |
Now let us implement some of the methods that we discussed above in a Java program. We will also see the following specific operations that involve two sets.
Set Implementation In Java
Intersection: We retain common values between the two sets. We perform an intersection using the retainAll method.
Union: Here we combine the two sets. This is done with the addAll method.
Difference: This operation removes one set from the other. This operation is performed using the removeAll method.
import java.util.*; public class Main { public static void main(String args[]) { //declare a set class (HashSet) Set<Integer> numSet = new HashSet<Integer>(); //add an element => add numSet.add(13); //add a list to the set using addAll method numSet.addAll(Arrays.asList(new Integer[] {1,6,4,7,3,9,8,2,12,11,20})); //print the set System.out.println("Original Set (numSet):" + numSet); //size() System.out.println("\nnumSet Size:" + numSet.size()); //create a new set class and initialize it with list elements Set<Integer> oddSet = new HashSet<Integer>(); oddSet.addAll(Arrays.asList(new Integer[] {1, 3, 7, 5, 9})); //print the set System.out.println("\nOddSet contents:" + oddSet); //contains () System.out.println("\nnumSet contains element 2:" + numSet.contains(3)); //containsAll () System.out.println("\nnumSet contains collection oddset:" + numSet.containsAll(oddSet)); // retainAll () => intersection Set<Integer> set_intersection = new HashSet<Integer>(numSet); set_intersection.retainAll(oddSet); System.out.print("\nIntersection of the numSet & oddSet:"); System.out.println(set_intersection); // removeAll () => difference Set<Integer> set_difference = new HashSet<Integer>(numSet); set_difference.removeAll(oddSet); System.out.print("Difference of the numSet & oddSet:"); System.out.println(set_difference); // addAll () => union Set<Integer> set_union = new HashSet<Integer>(numSet); set_union.addAll(oddSet); System.out.print("Union of the numSet & oddSet:"); System.out.println(set_union); } }
Output:
Original Set (numSet):[1, 2, 3, 4, 20, 6, 7, 8, 9, 11, 12, 13]
numSet Size:12
OddSet contents:[1, 3, 5, 7, 9]
numSet contains element 2:true
numSet contains collection oddset:false
Intersection of the numSet & oddSet:[1, 3, 7, 9]
Difference of the numSet & oddSet:[2, 4, 6, 8, 11, 12, 13, 20]
Union of the numSet & oddSet:[1, 2, 3, 4, 5, 6, 7, 8, 9, 11, 12, 13, 20]
Set To Array
We have seen the method ‘toArray’ in the above section on methods. This toArray method can be used to convert the set to an Array.
The Java program below converts the Set to an Array.
import java.util.*; public class Main { public static void main(String[] args) { //declare a set class (HashSet) Set<String> setOfColors= new HashSet<>(); // add data to HashSet setOfColors.add("Red"); setOfColors.add("Green"); setOfColors.add("Blue"); setOfColors.add("Cyan"); setOfColors.add("Magenta"); //print the set System.out.println("The set contents:" + setOfColors); //convert Set to Array using toArray () method String colors_Array[] = setOfColors.toArray(new String[setOfColors.size()]); //print the Array System.out.println("Set converted to Array:" + Arrays.toString(colors_Array)); } }
Output:
The set contents:[Red, Cyan, Blue, Magenta, Green]
Set converted to Array:[Red, Cyan, Blue, Magenta, Green]
Array To Set
To convert an Array to a set in Java, we can follow two approaches as shown below.
#1) We can convert the Array to a List using the asList method and then pass this list as an argument to the set constructor. This results in the set object being created with the array elements.
#2) Alternatively, we can use Collections.addAll method to copy the array elements to the set object.
The Java program below implements both these approaches to convert an array to set.
import java.util.*; public class Main { public static void main(String[] args) { //declare an array Integer[] numArray = {10,50,40,20,60,30,80,70}; System.out.println("The input array:" + Arrays.toString(numArray)); //Approach 1: create a set class and provide array //converted to list as constructor arg Set<Integer> numSet = new HashSet<>(Arrays.asList(numArray)); //print the set System.out.println("\nArray converted to set through asList:" + numSet); //create another set Set<Integer> intSet = new HashSet<>(); //Approach 2: use Collections.addAll method to copy array elements to the set Collections.addAll(intSet, numArray); //print the set System.out.println("\nArray converted to set using Collections.addAll:" + intSet); } }
Output:
The input array:[10, 50, 40, 20, 60, 30, 80, 70]
Array converted to set through asList:[80, 50, 20, 70, 40, 10, 60, 30]
Array converted to set using Collections.addAll:[80, 50, 20, 70, 40, 10, 60, 30]
Set To List
To convert set to a list in Java, we can use the ‘addAll’ method of the list class. This method copies the contents of the set or any collection provided as an argument to the list that invokes the addAll method.
The Java program below converts the set to an ArrayList.
import java.util.*; public class Main { public static void main(String[] args) { //declare a set class and initialize it Set<String> strSet= new HashSet<>(); strSet.add("one"); strSet.add("two"); strSet.add("three"); strSet.add("four"); strSet.add("five"); //print the set System.out.println("The set contents: " + strSet); //declare an ArrayList List<String> strList = new ArrayList<>(); //using addAll method,copy set elements to ArrayList strList.addAll(strSet); //print the ArrayList System.out.println("The ArrayList from set : " + strList); } }
Output:
The set contents: [four, one, two, three, five]
The ArrayList from set : [four, one, two, three, five]
List To Set
To convert the given list like ArrayList to a set in Java, we pass the list object as an argument to the constructor of the set.
The following Java program implements this conversion.
import java.util.*; public class Main { public static void main(String[] args) { //declare an ArrayList and initialize it List<String> strList = new ArrayList<>(); strList.add("one"); strList.add("two"); strList.add("three"); strList.add("four"); strList.add("five"); //print the ArrayList System.out.println("The ArrayList: " + strList); //declare a set class with ArrayList as argument to the constructor Set<String> strSet= new HashSet<>(strList); //print the set System.out.println("The Set obtained from ArrayList: " + strSet); } }
Output:
The ArrayList: [one, two, three, four, five]
The Set obtained from ArrayList: [four, one, two, three, five]
Sort A Set In Java
The Set collection in Java has no direct method of sorting. So we need to follow some indirect approaches for sorting or ordering the contents of the set object. However, there is an exception in case the set object is a TreeSet.
The TreeSet object by default provides the ordered set. Hence if we are keen on the ordered set of elements we should go for TreeSet. For HashSet or LinkedHashSet objects, we can convert the set to List. Sort the List using Collections.sort () method and then convert the list back to set.
This approach is shown in the below Java program.
import java.util.Arrays; import java.util.Collections; import java.util.*; public class Main{ public static void main(String[] args) { //Declare a set and initialize it with unsorted list HashSet<Integer> evenNumSet = new LinkedHashSet<>( Arrays.asList(4,8,6,2,12,10,62,40,36) ); //print the unsorted set System.out.println("Unsorted Set: " + evenNumSet); //convert set to list List<Integer> numList = new ArrayList<Integer>(evenNumSet); //Sort the list using Collections.sort () method Collections.sort(numList); //convert set to list evenNumSet = new LinkedHashSet<>(numList); //convert list to set //Print the sorted set System.out.println("Sorted Set:" + evenNumSet); } }
Output:
Unsorted Set: [4, 8, 6, 2, 12, 10, 62, 40, 36]
Sorted Set:[2, 4, 6, 8, 10, 12, 36, 40, 62]
List Vs Set In Java
Let’s discuss some of the differences between a list and a set.
List | Set |
---|---|
Implements List interface. | Implements Set interface. |
Contains a Legacy class, Vector. | No legacy classes. |
ArrayList, LinkedList is List Interface implementations. | HashSet, TreeSet, LinkedHashSet are Set implementations. |
An ordered sequence of elements. | An unordered collection of distinct elements. |
Allows duplicates. | No duplicates are allowed. |
Able to access elements as per the position of the element. | No positional access. |
Null values are allowed. | Only one null value allowed. |
New methods defined in a List interface. | No new methods defined in the Set interface. Collection interface methods are to be used with Set subclasses. |
Can be traversed in forward and backward direction using ListIterator. | It can be traversed only in the forward direction with Iterator. |
Frequently Asked Questions
Q #1) What is a Set in Java?
Answer: A set is an unordered collection of unique elements and typically models the concept of Set in mathematics.
Set is an interface that extends the Collection interface. It contains the methods that it inherits from the Collection interface. The set interface only adds a restriction i.e. no duplicates should be allowed.
Q #2) Is the Set ordered in Java?
Answer: No. Java Set is not ordered. It does not provide positional access as well.
Q #3) Can a Set contain duplicates?
Answer: A set is a collection of unique elements, it cannot have any duplicates.
Q #4) Is Java Set iterable?
Answer: Yes. The set interface implements an Iterable interface and thus set can be traversed or iterated using a forEach loop.
Q #5) Is NULL allowed in the set?
Answer: A set allows null value but at most one null value is allowed in set implementations like HashSet and LinkedHashSet. In the case of TreeSet, it throws runtime exception if the null is specified.
Conclusion
In this tutorial, we have discussed the general concepts and implementation related to Set interface in Java.
The set interface does not have any new methods defined, but it uses the methods of the Collector interface and only adds implementation to prohibit duplicate values. The set allows at most one null value.
In our subsequent tutorials, we will discuss specific implementations of the Set interface like HashSet and TreeSet.
=> Visit Here To Learn Java From Scratch.