Java – Set Example


Set interface is part of java.util package. Set interface can add value elements by add(value) method.
Set can implement TreeSet class.
Set value can get by Iterator interface.

Set Interface is part of java 1.2 and available in java 1.8 with addition of new method spliterator. Set do not allow any duplicate elements. Set can allow on null element. By name set it suggesting mathematical set abstraction. Set Interface extends Collection class.

1. To add object in set, can use add() method
2. To get object from set, can use Iterator Interface
3. To remove object from set, can use remove() method

Set example give a method, how to use Set in java.

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

public class SetExample {

    public static void main(String[] args) {

        // Set example with implement TreeSet
        Set<String> s=new TreeSet<String>();


        Iterator it=s.iterator();

          String value=(String);

          System.out.println("Value :"+value);


Set Value :a
Set Value :b
Set Value :c
Set Value :d



2 Responses to “Java – Set Example”

  1. NPK says:

    It’s a simple. Let me say that i have an Employee bean with name and age. If i create Employee object with same name and age and place it inside Set it will accept. Since i create Employee data in new Employee object. How to prevent the duplicate of Employee object from placing inside the set? Thanks in advance for the guidance.

  2. UncaAlby says:

    You need to provide an “equals()” method for the Employee class. That method determines if one Employee object is a “duplicate” of another Employee object. The “Set” automatically calls that method when you add a new element, and won’t add it if “equals()” returns “true”.

Leave a Reply