Set Interface

2. Set Interface

Set is a collection that cannot contain duplicate elements. The Set interface contains only methods inherited from Collection and adds the restriction that duplicate elements are prohibited. Below are few methods declared in the set interface. They are as follows:

Method Role
public boolean add() Add an element to the collection.
public void clear() Remove all element from the collection.
public boolean isEmpty() Check if collection is empty.
public boolean contains() Used to search an element.
public Iterator iterator() Returns an iterator.
public int size() Return total number of elements in the collection.
public boolean remove() Remove an element from the collection.

Let us see an example:

package collectionInterfaces;

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

public class SetTest {

  public static void main(String[] args) {
    Set<Integer> set = new HashSet<Integer>();
    int elements[] = {12,23,3,45,66,7,2,88};
    for(int i=0;i<elements.length;i++) {
      set.add(elements[i]);
    }
    System.out.println("Set element(s) -> " +set);
    
    Iterator<Integer> iterator = set.iterator();

    // Traverse set elements
    System.out.println("Traverse set elements: ");
    while(iterator.hasNext()) {
      System.out.println(iterator.next());
    }
    
    TreeSet<Integer> treeSet = new TreeSet<>(set);
    System.out.println("Sorted element(s) -> " +treeSet);
  }
}

Output:

Set element(s) -> [66, 2, 3, 23, 7, 88, 12, 45]
Traverse set elements: 
66
2
3
23
7
88
12
45
Sorted element(s) -> [2, 3, 7, 12, 23, 45, 66, 88]