Set in Java

Set in Java

Set interface is an unordered collection of elements but you can’t store duplicate values in Set.It does not maintain the insertion order.To use the set, we can use 4 classes.

1)HashSet

2)LinkedHashSet

3)EnumSet

4)TreeSet

We can create the implementation object for any of above classes:

HashSet:

If we don’t care about the insertion order and just need unique elements then we can should HashSet since performance is better than LinkedHashSet and TreeSet.It allows only one null value.HashSet uses HashMap internally to store the elements.

Syntax:

Set<Integer> priceSet = new HashSet<>();

LinkedHashSet:

If we want to maintain the insertion order then we should use LinkedHashSet.It too allows only one null value.LinkedHashSet uses LinkedHashMap internally to store elements.

Syntax:

LinkedHashSet linkedHashSet = new LinkedHashSet();

TreeSet:

If we want to sort the elements then we should go for TreeSet.It does not allow null values.TreeSet uses TreeMap internally to store data.

Syntax:

TreeSet treeObj = new TreeSet();

Example:

import java.util.Arrays;
import java.util.HashSet;
import java.util.LinkedHashSet;
import java.util.TreeSet;
class SetExamples {
    private static void testSet() {
        LinkedHashSet linkedHashSet = new LinkedHashSet<>();
        TreeSet treeSet = new TreeSet<>();
        HashSet hashSet = new HashSet();
        String[] fruits = {"Mango", "Apple", "Orange", "Banana", "Watermelon"};
        for (String str : Arrays.asList(fruits)) {
            linkedHashSet.add(str);
            treeSet.add(str);
            hashSet.add(str);
        }
        System.out.println("HashSet elements: " + hashSet);
        System.out.println("LinkedHashSet elements: " + linkedHashSet);
        System.out.println("TreeSet elements: " + treeSet);
    }
    public static void main(String args[]) {
        testSet();
    }
}
Output:
HashSet elements: [Apple, Watermelon, Mango, Orange, Banana]
LinkedHashSet elements: [Mango, Apple, Orange, Banana, Watermelon]
TreeSet elements: [Apple, Banana, Mango, Orange, Watermelon]    

Set Methods:
Below are the some useful methods which can be used.

Method Usage
add(Element E) Adds element to Set
addAll(Collection c) Adds all element from the provided set to Set on which this method is called
clear() Clear all the elements in the Set
remove(Element e) Removes the supplied element from Set
removeAll(Collection c) Removes all the elements from the supplied collection
size() returns the count the number of elements in the Set
contains(Object obj) Returns true if Set contains the provided element
toArray() Converts Set to object of Array
iterator() Removes the Iterator object which can be used for traversing elements in Set

Example:

import java.util.LinkedHashSet;
import java.util.Set;
public class Test {
    public static void main(String args[]) {
        Set addSet = new LinkedHashSet();
        addSet.add("First");
        addSet.add("Second");
        addSet.add("Third");
        addSet.add("Fourth");
        addSet.add("Fifth");
        addSet.add("Sixth");
        System.out.println("Add Set: " + addSet);
        Set add1Set = new LinkedHashSet();
        add1Set.add("Seven");
        add1Set.add("Eighth");
        addSet.addAll(add1Set);
        System.out.println("Final Set: " + addSet);
        System.out.println("Final Set size : " + addSet.size());
        addSet.remove("Fifth");
        System.out.println("Final Set after 'Fifth' removal : " + addSet);
        System.out.println("Final Set size after 'Fifth' removal : " + addSet.size());
        System.out.println("Set contains 'Third' element :" + addSet.contains("Third"));
        System.out.println("Set contains 'Tenth' element :" + addSet.contains("Tenth"));
        System.out.println("Set contains add1Set Set :" + addSet.containsAll(add1Set));
        addSet.clear();
        System.out.println("Final Set after clear: " + addSet);
        System.out.println("Is Final Set empty : " + addSet.isEmpty());
    }
}    

Output:

Add Set: [First, Second, Third, Fourth, Fifth, Sixth]
Final Set: [First, Second, Third, Fourth, Fifth, Sixth, Seven, Eighth]
Final Set size : 8
Final Set after 'Fifth' removal : [First, Second, Third, Fourth, Sixth, Seven, Eighth]
Final Set size after 'Fifth' removal : 7
Set contains 'Third' element :true
Set contains 'Tenth' element :false
Set contains add1Set Set :true
Final Set after clear: []
Is Final Set empty : true    

Read More :
All about Set
Other Resources

Leave a comment