Java Set Example


Java Java Set SetViews 2597

Java Set interface is an unordered collection of elements that do not contain any duplicate elements. The Set Interface provides features of the mathematical Set in java. In this tutorial, we will cover various Java set examples of Java set methods and their usage.

Features of Set interface

  • It contains unique elements which mean it does not allow duplicate values
  • Java Set does not have any order in storing the elements
  • It does not have any index and hence we cannot access any elements based on the position.
  • Since it is an interface, we can implement it using any of the Set implementation classes
  • Extends Collection interface

Difference between Java Set and Java List

  • Java Set is an unordered collection of elements whereas List is an ordered collection of elements.
  • Set does not have index-based access but List has an index with which we can access elements.
  • In Set, we cannot add duplicate values while List allows adding duplicate values.

Set Implementation

Since Java Set is an interface, we cannot create an object directly. Hence we need to implement one of the classes like HashSet, TreeSet, LinkedHashSet, or EnumSet. Each set class behaves in a different manner as discussed below:

  • HashSet – There is no order or sequence of elements while traversing through the set.
  • TreeSet – It preserves the order of elements along with sorting
  • LinkedHashSet – It preserves the order of elements the same as insertion

Set Java

Java Set Example

In order to implement the set interface, we need to import the java.util.* package else import the individual class packages separately.

import java.util.HashSet;
import java.util.LinkedHashSet;
import java.util.Set;
import java.util.TreeSet;

public class SetExample {

  public static void main(String[] args) {
    Set set1 = new HashSet();
    Set set2 = new TreeSet();
    Set set3 = new LinkedHashSet();

  }

}

We can also create Generic Sets as shown below. Here we have specified HashSet as String type and TreeSet as an Integer type. Hence these objects accept values only of these specific types.

import java.util.HashSet;
import java.util.Set;
import java.util.TreeSet;

public class SetExample {

  public static void main(String[] args) {
    Set<String> setstring = new HashSet<String>();
    Set<Integer> setint = new TreeSet<Integer>();
  }
}

Java Set methods

Set includes all the methods of Collection interface along with the below-mentioned methods.

MethodDescriptionParameter
boolean add(String e)Adds an element to the set if it does not already exist. It returns false if element already exists in the set and ignores the calle - the element to be added to the set
boolean addAll(Collectionc)Adds all the elements in the collection to the set if it does not presentc - collection of elements to be added
void clear()Removes all the elements from the set and set will be empty
boolean contains(Object o)Checks if the set contains the element and returns true if presento - element to be searched in the set
boolean containsAll(Collection c)Checks if the collection is a subset of the set and returns true if presentc - collection of elements
boolean equals(Object o)Checks the equality of the set with the object passed. It returns true if both are sets and contains same elements and sizeo - object which needs to be compared
boolean isEmpty()Checks if the set is empty or not and returns true if empty
Iterator iterator()Returns an iterator to navigate through the elements in the set
boolean remove(Object o)Removes the specific element from the set and returns true if the element is removedo - the element to be removed
boolean removeAll(Collection c)Removes all the elements in the collection from the set if presentc - collection of elements to be removed
boolean retainAll(Collection c)Retains only the elements in the collection in the set which means it removes all other elements which are not part of the collectionc - collection of elements to be retained
int size()Returns the number of elements in the set
SplitIterator splititerator()Creates a split iterator over the elements in the set
Object[] toArray()Converts all the elements in the set to array
String toString()Returns a string representation of the object

Set Exceptions

Java set throws the below exceptions

  • UnsupportedOperationException
  • NullPointerException
  • ClassCastException
  • IllegalArgumentException

Add and remove elements from a set

In the below example, we first create a HashSet and add 2 elements. Then we create another HashSet and add 2 more elements. This is then added as a collection to the first set.

In remove example, we first remove an element from the 1st set and then remove all elements from the second set.

import java.util.HashSet;
import java.util.LinkedHashSet;
import java.util.Set;
import java.util.TreeSet;

public class SetExample {

  public static void main(String[] args) {

    Set<String> setstring = new HashSet<String>();
    setstring.add("Java");
    setstring.add("Javascript");
    System.out.println(setstring);
    
    Set<String> string2 = new HashSet<String>();
    string2.add("C");
    string2.add("C++");
    
    setstring.addAll(string2);
    System.out.println("Elements in set after addAll operation");
    System.out.println(setstring);
    
    setstring.remove("Javascript");
    System.out.println("Elements in the set after remove opertaion");
    System.out.println(setstring);
    
    setstring.removeAll(string2);
    System.out.println("Elements in the set after removeAll opertaion");
    System.out.println(setstring);
    
  }
  

}
Output:
[Java, Javascript]
Elements in set after addAll operation
[Java, C++, C, Javascript]
Elements in the set after remove opertaion
[Java, C++, C]
Elements in the set after removeAll opertaion
[Java]

Sorting elements using TreeSet

Here, we have declared an array of integers and then added the elements to the HashSet using for loop. In the output, you can see that the duplicate element “12” is not included which is the set feature. We can sort the elements of HashSet using TreeSet as seen in the below example.

import java.util.*;

public class SetSort {

  public static void main(String[] args) {
    Set<Integer> numbers = new HashSet<Integer>();
    int[] a = {34,78,12,67,45,23,12,89};
    for(int i=0;i<a.length;i++) {
      numbers.add(a[i]);
    }
    System.out.println("Elements in HashSet");
    System.out.println(numbers);
    
    Set<Integer> treeset = new TreeSet<Integer>(numbers);
    System.out.println("Elements in treeset after sort");
    System.out.println(treeset);
  }

}
Output:
Elements in HashSet
[34, 67, 23, 89, 12, 45, 78]
Elements in treeset after sort
[12, 23, 34, 45, 67, 78, 89]

Convert Java Set to Array

We can convert set into an array of elements using the toArray method as described below.

import java.util.*;

public class SetArray {

  public static void main(String[] args) {
    Set<String> names = new HashSet<String>();
    names.add("Roshan");
    names.add("Kiran");
    names.add("Tejas");
    names.add("Karthik");
    
    String[] strnames = names.toArray(new String[names.size()]);
    for(String strvalues: strnames) {
      System.out.println(strvalues);
    }

  }

}
Output:
Roshan
Kiran
Tejas
Karthik

Example Java program of Set operations (Union, intersection, and difference)

In this example, we have created 2 integer sets. To perform a union of 2 sets, we use the addAll method, which will add all unique elements from both the sets. For intersection, we use the retainAll method to retain only the common elements between the sets. To find the difference between 2 sets, we use the removeAll method which will remove all elements in the set2 along with common elements in set1.

import java.util.*;

public class SetOperations {

  public static void main(String[] args) {
    Set<Integer> set1 = new HashSet<Integer>();
    set1.add(3);
    set1.add(7);
    set1.add(5);
    set1.add(1);
    System.out.println("Set 1 : " + set1);
    
    Set<Integer> set2 = new HashSet<Integer>();
    set2.add(3);
    set2.add(4);
    set2.add(9);
    set2.add(5);
    
    System.out.println("Set 2 : " + set2);
    
    Set<Integer> a = new HashSet<Integer>(set1);
    a.addAll(set2);
    
    System.out.println("Union of Set 1 and Set 2 : " + a);
    
    Set<Integer> b = new HashSet<Integer>(set1);
    b.retainAll(set2);
    System.out.println("Intersection of Set 1 and Set 2 : " + b);
    
    Set<Integer> c = new HashSet<Integer>(set1);
    c.removeAll(set2);
    System.out.println("Difference between Set 1 and Set 2 : " + c);
  }

}
Output:
Set 1 : [1, 3, 5, 7]
Set 2 : [3, 4, 5, 9]
Union of Set 1 and Set 2 : [1, 3, 4, 5, 7, 9]
Intersection of set 1 and set 2 : [3, 5]
Difference between 2 sets : [1, 7]

Conclusion

In this tutorial, you have learned about Set in Java and how to create and use set for different manipulations.

Reference

Translate ยป