Scientech Easy Java Set Interface | Example & Programs | Scientech Easy

Thursday, December 27, 2018

Java Set Interface | Example & Programs

In this tutorial, we will learn a very important topic Set interface in Java with example and programs. Basically, The Interface Set was introduced in Java 1.2 version. It is a kind of an unordered collection of elements which is used to remove the duplicate elements in the Java programming. It holds a single reference to an object. The set interface does not provide two references to the same object, two references to null, or references to two objects a and b  such that a.equals(b). 
Set does not provide any additional methods. It uses the methods defined by collection but places additional restrictions on those methods. When the set uses add() or addAll() methods defined by the collection interface, it does not add an element to the set if the set already contains that element. That means an element can exist only once in the set. Let's see in detail.

Set in Java


➲ A set in Java is a collection of elements or objects that are not stored in a particular order.
➲ It is used to store the collection of elements without duplicate. i.e. Set does not allow the duplicate elements. It contains the unique elements.
➲ It will not add an element to the set if the set already contains that element.
➲ It is an unordered collection. That means the order is not maintained while storing elements. While retrieving we may not get the same order as that we put elements.
➲ Java Set uses the Map based structure for their implementation. 
➲ Set can be iterated by using Iterator but cannot be iterated by using ListIterator.  
➲ Most of the set implementations allow adding only one null element. Treeset does not allow to add the null element. 
➲ Set is not indexed based structure in Java. Therefore, we cannot access elements by their index position. 
➲ It does not provide any get method like a list.

Set Hierarchy in Java


Java Set interface extends the java.util.collection interface. The java.util.SortedSet interface extends the set interface to provide the sorted set of elements. Three classes such as HashSet, LinkedHashSet, and TreeSet implements the set interface. ConcurrentSkipListSet and EnumSet classes also implements set interface. The hierarchy diagram of the set interface is shown in the below picture. 
Java set example, Java set methods

Java Set Methods


A set interface has the following various useful methods such as add, remove, clear, size etc to enhance the usage of a set interface in the collection framework. They are listed in the table.
SN Method Description
1 boolean add(Object o) It is used to add the specified element in this set.
2 boolean addAll(Collection c) This method adds all the elements in the given collection.
3 int size() It is used to get the number of elements in the set.
4 boolean isEmpty() This method checks that the set is empty or not.
5 void clear() It is used to remove all the elements from the set.
6 boolean contains(Object o) This method returns true if this set contains the given element.
7 boolean containsAll(Collection c) This method returns true if this set contains all the elements of the given collection.
8 boolean remove(Object o) It is used to remove the specified element from this set.
9 boolean removeAll(Collection c) It removes all the elements in the given collection from the set.
10 Iterator iterate() It returns an Iterator over the elements in this set.
11 boolean equals(Object o) It is used to compare the given element for equility in this set.
12 int hashCode() It is used to get the hashCode value for this set.

Ways to create a Generic Set object in Java


1. We can create a generic Set object by using the implementation of the HashSet, LInkedHashSet, TreeSet etc like this:
Syntax:
     Set<T> set=new HashSet<T>(); where T is the type of generic.
     Set<T> set=new LinkedHashSet<T>();
     Set<T> set=new TreeSet<T>();
For example:
      Set<Integer> set=new HashSet<Integer>();
      Set<String> set1=new LinkedHashSet<String>(); 

Performing Basic Operations on a Set with Example Programs


1. Adding Elements to a Set
The add() method returns true if the set does not contains the sepecfied element. If the set already contains the specified element then it will return false.
Program source code 1:
    package setPractice; import java.util.HashSet; import java.util.LinkedHashSet; import java.util.Set; public class SetExample1 { public static void main(String[] args) { // Create a generic set object of type string. Set<String> s=new HashSet<String>(); int size=s.size(); System.out.println("Size before adding elements: " +size); // Adding elements to the set. s.add("Orange"); s.add("Red"); s.add("Blue"); s.add("Yellow"); s.add("Green"); // Add duplicate elements in the set. These elements will be ignored by the set due to not taking the duplicate elements. s.add("Red"); s.add("Blue"); System.out.println("Unordered Set Elements"); System.out.println(s); // Check 'Black' element is present in the above set or not. if(s.equals("Black")){ System.out.println("Black element is not present in the set."); } else { s.add("Black"); System.out.println("Black is added successfully."); System.out.println("Set Elements after adding black element"); System.out.println(s); } // Create another set object to add the collection of elements to the above set. Set<String> s1=new LinkedHashSet<String>(); s1.add("White"); s1.add("Brown"); s1.add("Red"); // Duplicate element. // Call addAll() method to add all the elements of the given collection. s.addAll(s1); System.out.println("Set Element after adding elements from the given collection"); System.out.println(s); } }
    Output: Size before adding elements: 0 Unordered Set Elements [Red, Blue, Yellow, Orange, Green] Black is added successfully. Set Elements after adding black element [Red, Blue, Yellow, Black, Orange, Green] Set Element after adding elements from the given collection [Red, Brown, White, Blue, Yellow, Black, Orange, Green]
In the above example program, You can see that Set does not maintain the order of elements while storing. It gives unordered collection. When we add a duplicate element in the set, it rejected the duplicate element because the set does not allow the duplicate element (keep in mind these points).
2. Removing an Element from a Set
Program source code 2:
    package setPractice; import java.util.HashSet; import java.util.Set; public class SetExample2 { public static void main(String[] args) { // Create a generic set object of type string. Set<String> s=new HashSet<String>(); // Check the set is empty or not. boolean check=s.isEmpty(); // Return type of this method is an boolean. System.out.println("Is Set empty: " +check); // Adding elements to the set. s.add("Orange"); s.add("Red"); s.add("Blue"); s.add("Yellow"); s.add("Green"); if(s.isEmpty()){ System.out.println("Set is empty."); } else { System.out.println("Set is not empty."); System.out.println("Elements in the Set"); System.out.println(s); } // Remove an element from the set. s.remove("Blue"); System.out.println("Set elements after removing"); System.out.println(s); // Get the total number of set elements. int size=s.size(); System.out.println("Total number of elements: " +size); } }
    Output: Is Set empty: true Set is not empty. Elements in the Set [Red, Blue, Yellow, Orange, Green] Set elements after removing [Red, Yellow, Orange, Green] Total number of elements: 4
3. Searching an Element in a Set
Program source code 3:
    package setPractice; import java.util.HashSet; import java.util.Set; public class SetExample3 { public static void main(String[] args) { // Create a generic set object of type character. Set<Character> s=new HashSet<Character>(); // Adding elements to the set. s.add('D'); s.add('F'); s.add('H'); s.add('P'); s.add('K'); s.add(null); s.add(null); // Duplicate null element. Therefore, set allow only one null element. System.out.println("Unordered Set Elements"); System.out.println(s); // Call contains method to search the element. boolean search=s.contains('A'); // Returns false because A is not present in the set. System.out.println("Is Element A present in the set: " +search); if(s.contains('K')){ System.out.println("K is present in the set."); }else { System.out.println("K is not present in the set."); } int hashcode=s.hashCode(); System.out.println("HashCode value: " +hashcode); } }
    Output: Unordered Set Elements [P, null, D, F, H, K] Is Element A present in the set: false K is present in the set. HashCode value: 365

When to use Set in Java


1. If you want to represent a group of individual elements as a single entity where duplicates are not allowed and insertion order are not preserved then we should go for the Set.
2. If your requirement is to get the unique elements, the Set is the best choice for this.
3. If you want to remove duplicate elements without maintaining an insertion order from the non-set collection, you should go for the set.
Let's see a simple example program.
Program source code 4:
    package setPractice; import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Set; public class SetExample4 { public static void main(String[] args) { // Create a generic list object of type Integer. List<Integer> list=new ArrayList<Integer>(); int size=list.size(); System.out.println("Size before adding elements: " +size); // Adding elements to the set. list.add(5); list.add(10); list.add(5); list.add(15); list.add(20); list.add(10); list.add(20); list.add(30); System.out.println("Original order of List Elements"); System.out.println(list); Set<Integer> s=new HashSet<Integer>(list); System.out.println("Unodered List Elements after removing duplicate."); System.out.println(s); } }
    Output: Size before adding elements: 0 Original order of List Elements [5, 10, 5, 15, 20, 10, 20, 30] Unodered List Elements after removing duplicate. [20, 5, 10, 30, 15]
Final words 
We hope that this article will help you to understand the basic of Set Interface in Java with example and programs. In the next tutorial, we will see the difference between the list and set interface in a simple way.