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 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>();

        s.add("b");
        s.add("a");
        s.add("d");
        s.add("c");

        Iterator it=s.iterator();

        while(it.hasNext())
        {
          String value=(String)it.next();

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

Output

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

Tags:

 

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