Set is a child interface of the Collection interface that represents an unordered collection where each element is unique and cannot be repeated. It only consists of methods inherited from its parent interface and doesn’t allow duplicate elements. Further, if someone tries to add a duplicate via add() method, then it would return false, signifying the given element is not able to get added. It is part of java.util package.
It provides several essential methods that can be used to store, manipulate and search elements in a given set. It depicts a mathematical set and provides its abstraction.
There are various methods which implement the Set interface, including HashSet, LinkedHashSet and TreeSet.
SortedSet and NavigableSet interfaces further extend Set Interface that provides additional behaviour and different implementation to the existing method. NavigableSet is a child interface of SortedSet that provides navigational methods to navigate through a Set. It has a child class named TreeSet which is an implementation of the self-balancing tree.
How to declare and initialise a Set Object in Java?
Set interface provides specification only, in order to create its object, one requires its implementing class i.e HashSet,TreeSet, in order to create an object. With the help of Generics, we can specify the type of object that a Set Collection can store.
Set<T> set = new HashSet<T> ();
Point to Remember:
- It doesn’t preserve order of inserted elements
- It allows at most single null element
- It doesn’t allow duplicate elements
- It can have elements of different types
Methods of Set Interface
The methods supported by Set Interface are listed below :
Method Name | Explanation |
---|---|
add(Object) | The method adds an element in a given set, returns false if one tries to add duplicate element |
addAll(CollectionObj) | It adds all the elements of the given collection in a given set |
clear() | It removes all elements from the given set |
contains(Object) | It checks whether the given object consists in a set or not, if it returns true if exist, otherwise false |
containsAll(CollectionObj) | It returns true, if all the elements of the given collection exist in the set, otherwise false |
isEmpty() | It checks whether a set is empty or not. it returns if empty, other false |
iterator() | It provides iterator object to iterate through set |
remove(Object) | It removes the given object from the set, if present |
retainAll(CollectionObj) | It retains elements of the collection provided in the method, and removed all other elements in the set that don't match the elements of collection object |
size() | It returns number of elements present in a set |
spliterator() | it returns spliterator object to iterate through set |
toArray() | It converts given set and returns array |
removeAll(CollectionObj) | It removes all the elements consisting in the collection object |
Java Program to demonstrate working of Set interface
Program:
import java.util.HashSet; import java.util.Set; public class SetExample { public static void main(String[] args) { Set<String> set = new HashSet<>() ; // Creating set object set.add("The"); set.add("Programmerbay"); set.add("Code"); set.add("Example"); System.out.println("Printing Added element :: "+set); set.add("Code"); // Adding duplicate element System.out.println("Duplicate element not present :: "+set); set.remove("Example"); // Removing duplicate element System.out.println("Removing 'Example' element :: "+set); } }
Output:
Printing Added element :: [The, Example, Code, Programmerbay] Duplicate element not present :: [The, Example, Code, Programmerbay] Removing 'Example' element :: [The, Code, Programmerbay]
Basic Operations Supported by Set and Its implementing Classes
1) Add Elements :
Set interface specifies add(object) and addAll(CollectionObj) to add elements to a set. It doesn’t preserves insertion order of inserted elements. In contrast, it uses hashing mechanism to store elements where a hash of an element is generated and stored in a hash table. As mentioned before, it doesn’t allow duplicates, but accepts atmost single null value.
Java program to add single element and multiple elements in a Set using add() and addAll() method
Program:
public class SetExample { public static void main(String[] args) { Set<String> set = new HashSet<>() ; // Creating set object Collection<String> collection = List.of( "Another","Collection","inserted"); set.add("Programmerbay"); System.out.println("Single Added element :: "+set); set.addAll(collection); // Adding collection elements, but order will not be preserved System.out.println("Collection added to set :: "+ set); } }
Output:
Single Added element :: [Programmerbay] Collection added to set :: [inserted, Collection, Programmerbay, Another]
2) Remove Elements:
Set interface offers three methods for this, however, all have different use cases.
1) remove() -> It removes a single element
2) removeAll() -> It accepts a collection object and removes all elements that match the targeted set.
3) retainAll () -> Opposite to removeAll(), it accepts a collection object and persists only those elements that match with the provided collection, other elements that are present in the targeted set get removed.
Java program to remove single element and multiple elements in a Set using remove() and removeAll() method
Program:
public class SetExample { public static void main(String[] args) { Set<String> set = new HashSet<>() ; // Creating set object Collection<String> retainObjs = List.of("Programmerbay","Code"); Collection<String> removeAllObj = List.of("Remove1","Remove2"); // Adding random elements set.add("Remove Me"); set.add("Remove1"); set.add("Remove2"); set.add("Programmerbay"); set.add("Example"); set.add("The"); set.add("Code"); System.out.println("Elements :: "+set); // removing 'remove Me' from the list set.remove("Remove Me"); System.out.println("After single remove :: "+set); set.removeAll(removeAllObj); // remove1 and remove2 stored in removeAllObj would remove elements in set System.out.println("after removeAll() :: "+ set); set.retainAll(retainObjs); // Programmerbay and Code stored in reainAllObj would store elements and remove others from the set System.out.println("after retainAll() :: "+ set); } }
Output:
Elements :: [The, Remove1, Remove2, Remove Me, Example, Code, Programmerbay] After single remove :: [The, Remove1, Remove2, Example, Code, Programmerbay] after removeAll() :: [The, Example, Code, Programmerbay] after retainAll() :: [Code, Programmerbay]
4) Iterate over Elements:
There are multiple ways to iterate over elements of a set. These are the following:
1) using iterator
2) Using forEach()
3) Using Java 8 Stream
Java program to iterate over elements of a set.
program:
public class SetExample { public static void main(String[] args) { Set<String> set = new HashSet<>() ; // Creating set object // Adding random elements set.add("Remove Me"); set.add("Remove1"); set.add("Remove2"); set.add("Programmerbay"); set.add("Example"); set.add("The"); set.add("Code"); Iterator iterator = set.iterator(); // fetching iterator object of the set System.out.println("Iterating through iterator object :: "); while (iterator.hasNext()){ System.out.println(iterator.next()); } // using for each System.out.println("Iterating through for each loop :: "); for (String element: set) { System.out.println( element); } // using Java 8 Stream System.out.println("Iterating through using java 8 stream :: "); set.stream().forEach(e -> System.out.println("element :: "+ e)); } }
Output:
Iterating through iterator object :: The Remove1 Remove2 Remove Me Example Code Programmerbay Iterating through for each loop :: The Remove1 Remove2 Remove Me Example Code Programmerbay Iterating through using java 8 stream :: element :: The element :: Remove1 element :: Remove2 element :: Remove Me element :: Example element :: Code element :: Programmerbay
Implementing Classes of Set Interface
HashSet class : Hashset class is a implementing class of Set interface that uses hash table as its underlying data structure. It doesn’t preserves insertion order,meaning, the order in which elements are inserted may differ as it hash code to insert data. It accepts null values.
public class SetExample { public static void main(String[] args) { Set<String> set = new HashSet<>() ; // Creating set object set.add("Programmerbay"); set.add("Example"); System.out.println(set); } }
Output:
[Example, Programmerbay]
LinkedHashSet class : It also implements Set interface and exhibits the behavior of doubly linked list. Unlike HashSet, it preserves insertion order.
public class SetExample { public static void main(String[] args) { Set<String> set = new LinkedHashSet<>() ; // Creating set object set.add("Programmerbay"); set.add("Example"); System.out.println(set); } }
Output:
[Programmerbay, Example]
TreeSet class : It is a implementation class of SortedSet interface. It resembles tree data structure to store and manage data. It stores data in natural sorting order.
public class SetExample { public static void main(String[] args) { Set<String> set = new TreeSet<>() ; // Creating set object set.add("Programmerbay"); set.add("Example"); System.out.println(set); } }
Output:
[Example, Programmerbay]