Set Collections in Java

Set Collections in Java with Examples

In this article, I am going to discuss Set Collections in Java with Examples. Please read our previous article where we discussed Cursors of Collection Framework in Java. As part of this article, we are going to discuss the following pointers in detail.

  1. Set Interface in Java collection framework
  2. Classes Implement the Set Interface
  3. HashSet Collection in Java
  4. LinkedHashSet Collection in Java
  5. TreeSet Collection in Java
  6. Comparison Between HashSet, LinkedHashSet and TreeSet in Java
  7. SortedSet Collection in Java
Set Interface in Java collection framework

The Set interface of the Java Collections framework provides the features of the mathematical set in Java. It extends the Collection interface. Unlike the List interface, sets cannot contain duplicate elements. Since Set is an interface, we cannot create objects from it.

Classes of Set Interface

In order to use functionalities of the Set interface, we can use these classes:

  1. HashSet
  2. LinkedHashSet
  3. TreeSet
  4. SortedSet

These classes are defined in the Collections framework and implement the Set interface.

HashSet Collection in Java

The HashSet is the implementation class of Set interface which is also used to store a group of individual objects but duplicate values are not allowed. HashSet internally follows a hashtable structure where all the elements are stored using a hashing technique which will improve the performance by reducing the waiting time.

The HashSet is not a synchronized class. HashSet supports only one null value. HashSet is called unordered collection because it is no guaranteed for the insertion order of elements.

Creation of HashSet
Syntax : HashSet<Integer> numbers = new HashSet<>(8, 0.75);
Here, we have created a hash set named numbers.

Notice, the part new HashSet<>(8,0.75). Here, the first parameter is capacity, and the second parameter is the load factor.

  1. capacity – The capacity of this hash set is 8. Meaning, it can store 8 elements.
  2. loadFactor – The load factor of this hash set is 0.6. This means, whenever our hash set is filled by 60%, the elements are moved to a new hash table of double the size of the original hash table.
Constructors of HashSet

HashSet<E> hs = new HashSet<E>();
It is used to construct a default HashSet.

HashSet<E> hs = new HashSet<E>(int capacity);
It is used to initialize the capacity of the hash set to the given integer value capacity.

HashSet<E> hs = new HashSet<E>(int capacity, float loadFactor);
It is used to initialize the capacity of the hash set to the given integer value capacity and the specified load factor.

HashSet<E> hs = new HashSet<E>(Collection obj);
It is used to initialize the hash set by using the elements of the collection obj.

Methods of HashSet Collection in Java:
  1. boolean add(E obj): It adds the element e to the list.
  2. boolean remove(E obj): It removes the specified Object o from the Set.
  3. int size(): It gives the number of elements of a Set.
  4. void clear(): It removes all the elements from the list.
  5. boolean contains(E obj): It checks whether the specified Object o is present in the list or not. If the object has been found it returns true else false.
  6. boolean isEmpty(): Returns true if there is no element present in the Set.
  7. Object clone(): This method returns a shallow copy of the HashSet.
Sample Program to demonstrate HashSet Collection in Java
import java.util.*;
public class HashSetDemo {
 public static void main(String[] args) {
  HashSet<Integer> hs = new HashSet<Integer>();
  hs.add(17);
  hs.add(13);
  hs.add(27);
  hs.add(12);
  hs.add(45);
  System.out.println(hs);
  System.out.println(hs.size());
  for(int e:hs) {
   System.out.println(e);
  }
  Iterator it = hs.iterator();
  while(it.hasNext()) {
   System.out.println(it.next());
  }
 }
}

Output:

HashSet Collection in Java

HashSet Example with Complex Data type in Java:
import java.util.HashSet;
public class HashSetDemo
{
    public static void main (String a[])
    {
        HashSet < Price > hashSet = new HashSet < Price > ();
        hashSet.add (new Price ("Banana", 20));
        hashSet.add (new Price ("Apple", 40));
        hashSet.add (new Price ("Orange", 30));
        for (Price pr:hashSet)
        {
         System.out.println (pr);
        }
        Price key = new Price ("Banana", 20);
        System.out.println ("Does set contains key? " + hashSet.contains (key));
    }
}

class Price
{
    private String item;
    private int price;

    public Price (String itm, int pr)
    {
        this.item = itm;
        this.price = pr;
    }

    public int hashCode ()
    {
        System.out.println ("In hashcode");
        int hashcode = 0;
        hashcode = price * 20;
        hashcode += item.hashCode ();
        return hashcode;
    }

    public boolean equals (Object obj)
    {
        System.out.println ("In equals");
        if (obj instanceof Price)
        {
         Price pp = (Price) obj;
         return (pp.item.equals (this.item) && pp.price == this.price);
        }
        else
        {
         return false;
        }
    }

    public String getItem ()
    {
        return item;
    }
    public void setItem (String item)
    {
        this.item = item;
    }
    public int getPrice ()
    {
        return price;
    }
    public void setPrice (int price)
    {
        this.price = price;
    }

    public String toString ()
    {
        return "item: " + item + "  price: " + price;
    }
}

Output:

HashSet Example with Complex Data type in Java

LinkedHashSet Collection in Java:

LinkedHashSet is the implementation class of Set interface which is also used to store a group of individual objects but duplicate values are not allowed. The LinkedHashSet internally follows hashtable + double linked list structures.

LinkedHashSet is not a synchronized class. LinkedHashSet supports only one null value. LinkedHashSet is called as ordered Collection because it is a guarantee for the insertion order of elements.

Creation of LinkedHashSet
Syntax : LinkedHashSet<Integer> numbers = new LinkedHashSet<>(8, 0.75);
Notice, the part new LinkedHashSet<>(8,0.75). Here, the first parameter is capacity and the second parameter is loadFactor.

LinkedHashSet Constructors

LinkedHashSet<E> lhs = new LinkedHashSet<E>();
It is used to construct a default LinkedHashSet.

LinkedHashSet<E> lhs = new LinkedHashSet<E>(int capacity);
It is used to initialize the capacity of the Linked hash set to the given integer value capacity.

LinkedHashSet<E> lhs = new LinkedHashSet<E>(int capacity, float loadFactor);
It is used to initialize the capacity of the Linked hash set to the given integer value capacity and the specified load factor.

LinkedHashSet<E> lhs = new LinkedHashSet<E>(Collection obj);
It is used to initialize the Linked hash set by using the elements of the collection obj.

Sample Program to demonstrate LinkedHashSet Collection in Java
import java.util.*;
class LinkedHashSetDemo
{
    public static void main (String args[])
    {
        //Creating HashSet and adding elements  
        LinkedHashSet < String > set = new LinkedHashSet ();
        set.add ("One");
        set.add ("Two");
        set.add ("Three");
        set.add ("Four");
        set.add ("Five");
        Iterator < String > i = set.iterator ();
        while (i.hasNext ())
        {
         System.out.println (i.next ());
        }
    }
}

Output:

Linked Hash Set Collection in Java

LinkedHashSet Example with Complex Data type in Java:
import java.util.LinkedHashSet;
public class LinkedHashSetDemo
{
    public static void main (String a[])
    {
        LinkedHashSet < Price > lhs = new LinkedHashSet < Price > ();
        lhs.add (new Price ("Banana", 20));
        lhs.add (new Price ("Apple", 40));
        lhs.add (new Price ("Orange", 30));
        for (Price pr:lhs)
        {
         System.out.println (pr);
        }
        Price key = new Price ("Banana", 20);
        System.out.println ("Does set contains key? " + lhs.contains (key));
    }
}

class Price
{
    private String item;
    private int price;

    public Price (String itm, int pr)
    {
        this.item = itm;
        this.price = pr;
    }

    public int hashCode ()
    {
        System.out.println ("In hashcode");
        int hashcode = 0;
        hashcode = price * 20;
        hashcode += item.hashCode ();
        return hashcode;
    }

    public boolean equals (Object obj)
    {
        System.out.println ("In equals");
        if (obj instanceof Price)
        {
         Price pp = (Price) obj;
         return (pp.item.equals (this.item) && pp.price == this.price);
        }
        else
        {
         return false;
        }
    }

    public String getItem ()
    {
        return item;
    }
    public void setItem (String item)
    {
        this.item = item;
    }
    public int getPrice ()
    {
        return price;
    }
    public void setPrice (int price)
    {
        this.price = price;
    }

    public String toString ()
    {
        return "item: " + item + "  price: " + price;
    }
}

Output:

LinkedHashSet Example with Complex Data type in Java

TreeSet Collection in Java:

TreeSet is the implementation class of Set interface which is also used to store a group of individual objects but duplicate values are not allowed. The TreeSet internally follows the tree structure.

The TreeSet is not a synchronized class. TreeSet is called an unordered collection because it is not guaranteed for insertion order of elements but all elements are stored in sorted order (by default ascending order).

The TreeSet supports only one null value if TreeSet is empty otherwise TreeSet does not support null values because it internally performs comparison operations but we never compare a null value with any object and it will throw a RuntimeException saying NullPointerException.

The TreeSet does not allow to store different types of objects because it internally performs comparison operations but we never compare two different types of object and it will throw a runtime exception saying ClassCastException.

Creation of TreeSet
Syntax : TreeSet<Integer> numbers = new TreeSet<Integer>();
Here, we have created a TreeSet without any arguments. In this case, the elements in TreeSet are sorted naturally (ascending order).

TreeSet Constructors

TreeSet<E> ts = new TreeSet<E>();
It is used to construct an empty tree set that will be sorted in ascending order according to the natural order of the tree set.

TreeSet<E> ts = new TreeSet<E>(SortedSet);
It is used to build a TreeSet that contains the elements of the given SortedSet.

TreeSet<E> ts = new TreeSet<E>(Comparator);
It is used to construct an empty tree set that will be sorted according to the given comparator.

TreeSet<E> ts = new TreeSet<E>(Collection obj);
It is used to build a new tree set that contains the elements of the collection obj.

Methods of TreeSet
  1. E ceiling(E e): It returns the equal or closest greatest element of the specified element from the set, or null there is no such element.
  2. E floor(E e): It returns the equal or closest least element of the specified element from the set, or null there is no such element.
  3. E higher(E e): It returns the closest greatest element of the specified element from the set, or null there is no such element.
  4. E lower (E e): It returns the closest least element of the specified element from the set, or null there is no such element.
  5. E pollFirst(): It is used to retrieve and remove the lowest(first) element.
  6. E pollLast(): It is used to retrieve and remove the highest(last) element.
Sample Program to demonstrate TreeSet Collection in Java
import java.util.TreeSet;
public class TreeSetDemo
{
    public static void main (String args[])
    {
        // TreeSet of String Type
        TreeSet < String > tset = new TreeSet < String > ();

        // Adding elements to TreeSet<String>
        tset.add ("ABC");
        tset.add ("String");
        tset.add ("Test");
        tset.add ("Pen");
        tset.add ("Ink");
        tset.add ("Jack");

        //Displaying TreeSet
        System.out.println (tset);

        // TreeSet of Integer Type
        TreeSet < Integer > tset2 = new TreeSet < Integer > ();

        // Adding elements to TreeSet<Integer>
        tset2.add (88);
        tset2.add (7);
        tset2.add (101);
        tset2.add (0);
        tset2.add (3);
        tset2.add (222);
        System.out.println (tset2);
    }
}

Output:

Tree Set Collection in Java

TreeSet Example with Complex Data type in Java:
import java.util.Comparator;
import java.util.Objects;
import java.util.SortedSet;
import java.util.TreeSet;

class Employee implements Comparable < Employee >
{
    private int id;
    private String name;

    public Employee (int id, String name)
    {
        this.id = id;
        this.name = name;
    }

    public int getId ()
    {
        return id;
    }

    public void setId (int id)
    {
        this.id = id;
    }

    public String getName ()
    {
        return name;
    }

    public void setName (String name)
    {
        this.name = name;
    }

    // Two Employees are equal if their IDs are equal
    @Override public boolean equals (Object o)
    {
        if (this == o)
            return true;
        if (o == null || getClass () != o.getClass ())
            return false;
        Employee employee = (Employee) o;
            return id == employee.id;
    }

    @Override public int hashCode ()
    {
        return Objects.hash (id);
    }

    // Compare employees based on their IDs
    @Override public int compareTo (Employee employee)
    {
        return this.getId () - employee.getId ();
    }

    @Override public String toString ()
    {
        return "Employee{" + "id=" + id + ", name='" + name + '\'' + '}';
    }
}

public class TreeSetUserDefinedObjectExample
{
    public static void main (String[]args)
    {
        TreeSet < Employee > employees = new TreeSet <> ();

        // TreeSet uses the compareTo() method of the Employee class to compare two
        // employees and sort them
        employees.add (new Employee (1010, "Rajeev"));
        employees.add (new Employee (1005, "Sachin"));
        employees.add (new Employee (1008, "Chris"));

        System.out.println ("Employees Sorted");
        System.out.println (employees);
    }
}

Output:

TreeSet Example with Complex Data type in Java

Comparison Between HashSet, LinkedHashSet and TreeSet in Java

Comparison Between HashSet, LinkedHashSet and TreeSet in Java

SortedSet Collection in Java:

The SortedSet interface extends Set and declares the behavior of a set sorted in ascending order. Several methods throw a NoSuchElementException when no items are contained in the invoking set.

A ClassCastException is thrown when an object is incompatible with the elements in a set. A NullPointerException is thrown if an attempt is made to use a null object and null is not allowed in the set.

SortedSet Methods in Java
  1. Object first(): Returns the first element in the invoking sorted set.
  2. SortedSet headSet(Object end): Returns a SortedSet containing those elements less than the end that are contained in the invoking sorted set. Elements in the returned sorted set are also referenced by the invoking sorted set.
  3. Object last(): Returns the last element in the invoking sorted set.
  4. SortedSet subSet(Object start, Object end): Returns a SortedSet that includes those elements between start and end.1. Elements in the returned collection are also referenced by the invoking object.
  5. SortedSet tailSet(Object start): Returns a SortedSet that contains those elements greater than or equal to start that are contained in the sorted set. Elements in the returned set are also referenced by the invoking object.
Sample Program to demonstrate SortedSet Collection in Java
import java.util.*;
class SortedSetDemo
{
    public static void main (String args[])
    {
        TreeSet < String > set = new TreeSet < String > ();
        set.add ("A");
        set.add ("B");
        set.add ("C");
        set.add ("D");
        set.add ("E");

        System.out.println ("Intial Set: " + set);
        System.out.println ("Head Set: " + set.headSet ("C"));
        System.out.println ("SubSet: " + set.subSet ("A", "E"));
        System.out.println ("TailSet: " + set.tailSet ("C"));
    }
}

Output:

SortedSet Collection in Java

In the next article, I am going to discuss Queue Collections in Java with examples. Here, in this article, I try to explain Set Collections in Java with Examples and I hope you enjoy this Set Collections in Java with Examples article.

Leave a Reply

Your email address will not be published. Required fields are marked *