DEV Community

PRIYA K
PRIYA K

Posted on

Set in Collections in Java

https://www.w3schools.com/java/java_set.asp
https://www.geeksforgeeks.org/java/set-in-java/
https://www.tutorialspoint.com/java/java_set_interface.htm

A Set is a Collection that cannot contain duplicate elements. It models the mathematical set abstraction.

The Set interface contains only methods inherited from Collection and adds the restriction that duplicate elements are prohibited.

Set also adds a stronger contract on the behavior of the equals and hashCode operations, allowing Set instances to be compared meaningfully even if their implementation types differ.

The Set interface is a part of the Java Collection Framework, located in the java.util package.
It models the mathematical set abstraction.
It represents a collection of unique elements, meaning it does not allow duplicate values.
The Set interface contains only methods inherited from Collection and adds the restriction that duplicate elements are prohibited.

The Set interface of the Java Collections framework provides the features of the mathematical set in Java. It extends the Collection interface.

Set also adds a stronger contract on the behavior of the equals and hashCode operations, allowing Set instances to be compared meaningfully even if their implementation types differ.

The set interface does not allow duplicate elements.
It can contain at most one null value except TreeSet implementation which does not allow null.
The set interface provides efficient search, insertion, and deletion operations.
Enter fullscreen mode Exit fullscreen mode

Set does not allow duplicates, and it does not preserve the order of elements (unless you're using TreeSet or LinkedHashSet).

Common classes that implement Set:

HashSet - fast and unordered
TreeSet - sorted set
LinkedHashSet - ordered by insertion
Enter fullscreen mode Exit fullscreen mode

Use a Set when you need to store unique values only.

Classes that implement Set
Since Set is an interface, we cannot create objects from it.
In order to use functionalities of the Set interface, we can use these classes:
HashSet
LinkedHashSet
EnumSet
TreeSet
These classes are defined in the Collections framework and implement the Set interface.

Interfaces that extend Set
The Set interface is also extended by these subinterfaces:
SortedSet
NavigableSet

How to use Set?
In Java, we must import java.util.Set package in order to use Set.

// Set implementation using HashSet
Set<String> animals = new HashSet<>();
Enter fullscreen mode Exit fullscreen mode

Here, we have created a Set called animals. We have used the HashSet class to implement the Set interface.

Set Operations
The Java Set interface allows us to perform basic mathematical set operations like union, intersection, and subset.

Union - to get the union of two sets x and y, we can use x.addAll(y)
Intersection - to get the intersection of two sets x and y, we can use x.retainAll(y)Set Operations
Subset - to check if x is a subset of y, we can use y.containsAll(x)
Enter fullscreen mode Exit fullscreen mode

Common Set Methods

The Set interface includes all the methods of the Collection interface. It's because Collection is a super interface of Set.

Some of the commonly used methods of the Collection interface that's also available in the Set interface are:

add()

Adds an element if it's not already in the set.Adds an object to the collection.

addAll()
adds all the elements of the specified collection to the set

containsAll()
returns true if the set contains all the elements of the specified collection

toArray()
returns an array containing all the elements of the set

remove()

Removes the element from the set.
Removes a specified object from the collection.

removeAll()
removes all the elements from the set that is present in another specified set

contains()

Checks if the set contains the element.
Returns true if a specified object is an element within the collection.
returns true if the set contains the specified element

size()

Returns the number of elements in the collection.
returns the length (number of elements) of the set

clear()

Removes all elements.Removes all objects from the collection.

retainAll()
retains all the elements in the set that are also present in another specified set

isEmpty( )
Returns true if the collection has no elements.

hashCode()
returns a hash code value (address of the element in the set)

iterator( )
Returns an Iterator object for the collection, which may be used to retrieve an object.
returns an iterator that can be used to access elements of the set sequentially

Set vs. List
List Set
Allows duplicates Does not allow duplicates
Maintains order Does not guarantee order
Access by index No index-based access

Declaration of Set Interface

    public interface Set<E> extends Collection <E>
Enter fullscreen mode Exit fullscreen mode
import java.util.HashSet;
import java.util.Set;
public class Geeks {
    public static void main(String args[]) 
    {
        // Create a Set using HashSet
        Set<String> s = new HashSet<>();
        // Displaying the Set
        System.out.println("Set Elements: " + s);
    }
}
Enter fullscreen mode Exit fullscreen mode

Explanation: In the above example, HashSet will appear as an empty set, as no elements were added. The order of elements in HashSet is not guaranteed, so the elements will be displayed in a random order if any are added.

Hierarchy of Set interface

Classes that implement the Set interface

HashSet: A set that stores unique elements without any specific order, using a hash table and allows one null element.
EnumSet : A high-performance set designed specifically for enum types, where all elements must belong to the same enum.
LinkedHashSet: A set that maintains the order of insertion while storing unique elements.
TreeSet: A set that stores unique elements in sorted order, either by natural ordering or a specified comparator.
Enter fullscreen mode Exit fullscreen mode

Creating Set Objects

Since Set is an interface, objects cannot be created of the typeset. We always need a class that implements this interface in order to create an object. it is possible to restrict the type of object that can be stored in the Set. This type-safe set can be defined as:

    // Obj is the type of the object to be stored in Set 
    Set<Obj> set = new HashSet<Obj> (); 
Enter fullscreen mode Exit fullscreen mode

Performing Various Operations on Set

Set interface provides commonly used operations to manage unique elements in a collection.

1. Adding Elements
To add elements to a Set in Java, use the add() method.

import java.util.*;
// Main class
class Geeks {
    public static void main(String[] args)
    {
        Set<String> s = new HashSet<String>();
        s.add("B");
        s.add("B");
        s.add("C");
        s.add("A");
        System.out.println(s);
    }
}
Enter fullscreen mode Exit fullscreen mode

Output
[A, B, C]

2. Accessing the Elements
After adding the elements, if we wish to access the elements, we can use inbuilt methods like contains().

import java.util.*;
class Geeks {
    public static void main(String[] args)
    {
        Set<String> h = new HashSet<String>();
        h.add("A");
        h.add("B");
        h.add("C");
        h.add("A");
        System.out.println("Set is " + h);
        String s = "D";
        System.out.println("Contains " + s + " " + h.contains(s));
    }
}
Enter fullscreen mode Exit fullscreen mode

Output
Set is [A, B, C]
Contains D false

3. Removing Elements
The values can be removed from the Set using the remove() method.

import java.util.*;
class Geeks {
    public static void main(String[] args)
    {
        // Declaring object of Set of type String
        Set<String> h = new HashSet<String>();
        // Elements are added using add() method, Custom input elements
        h.add("A");
        h.add("B");
        h.add("C");
        h.add("B");
        h.add("D");
        h.add("E");
        System.out.println("Initial HashSet " + h);
        // Removing custom element using remove() method
        h.remove("B");
        System.out.println("After removing element " + h);
    }
}
Enter fullscreen mode Exit fullscreen mode

Output
Initial HashSet [A, B, C, D, E]
After removing element [A, C, D, E]

4. Iterating elements
There are various ways to iterate through the Set. The most famous one is to use the enhanced for loop.

import java.util.*;
class Geeks {
public static void main(String[] args)
{
// Creating object of Set and declaring String type
Set h = new HashSet();
// Adding elements to Set using add() method, Custom input elements
h.add("A");
h.add("B");
h.add("C");
h.add("B");
h.add("D");
h.add("E");
// Iterating through the Set via for-each loop
for (String value : h)
// Printing all the values inside the object
System.out.print(value + ", ");
System.out.println();
}
}

Output
A, B, C, D, E,

Methods of Set Interface

add(element)

Adds element if not already present. Returns true if added.

addAll(collection)

Adds all elements from the given collection.

clear()
Removes all elements from the set.

contains(element)

Checks if the set contains the specified element.

containsAll(collection)
Checks if the set contains all elements from the given collection.

hashCode()

Returns the hash code of the set.

isEmpty()

This method is used to check whether the set is empty or not.

iterator()

This method is used to return the iterator of the set.

remove(element)
Removes the specified element from the set.

removeAll(collection)

Removes all elements in the given collection from the set.

retainAll(collection)

Retains only elements present in the given collection.

size()

Returns the number of elements in the set.

toArray()

This method is used to form an array of the same elements as that of the Set.

Set Interface Examples

Set has its implementation in various classes like HashSet, TreeSet, LinkedHashSet.

Example to Implement Set Using HashSet

import java.util.HashSet;
import java.util.Set;
public class SetDemo {
  public static void main(String args[]) { 
      int count[] = {34, 22,10,60,30,22};
      Set<Integer> set = new HashSet<>();
      try {
         for(int i = 0; i < 5; i++) {
            set.add(count[i]);
         }
         System.out.println(set);
      }
      catch(Exception e) {}
   }
} 
Enter fullscreen mode Exit fullscreen mode

Output
[34, 22, 10, 60, 30]

Example to Implement Set Using TreeSet

import java.util.HashSet;
import java.util.Set;
import java.util.TreeSet;
public class SetDemo {
  public static void main(String args[]) { 
      int count[] = {34, 22,10,60,30,22};
      Set<Integer> set = new HashSet<>();
      try {
         for(int i = 0; i < 5; i++) {
            set.add(count[i]);
         }
         System.out.println(set);

         TreeSet<Integer> sortedSet = new TreeSet<>(set);
         System.out.println("The sorted list is:");
         System.out.println(sortedSet);
         System.out.println("The First element of the set is: "+ (Integer)sortedSet.first());
         System.out.println("The last element of the set is: "+ (Integer)sortedSet.last());
      }
      catch(Exception e) {}
   }
}
Enter fullscreen mode Exit fullscreen mode

Output
[34, 22, 10, 60, 30]

The sorted list is:
[10, 22, 30, 34, 60]
The First element of the set is: 10
The last element of the set is: 60

Example to Implement Set Using LinkedHashSet

import java.util.LinkedHashSet;
import java.util.Set;
public class SetDemo {
  public static void main(String args[]) { 
      int count[] = {34, 22,10,60,30,22};
      Set<Integer> set = new LinkedHashSet<>();
      try {
         for(int i = 0; i < 5; i++) {
            set.add(count[i]);
         }
         System.out.println(set);
      }
      catch(Exception e) {}
   }
}  
Enter fullscreen mode Exit fullscreen mode

Output
[34, 22, 10, 60, 30]

Top comments (0)