top of page
Writer's picturePushp Raj

Set in Java: Methods and Operations



Set is an interface defined in Java.util package. It enhances the collection interface to create an unordered collection or list with no duplicate values. As the name implies, a set in Java is used to generate a mathematical set. Because the set extends the collection interface, duplicate elements are not permitted. The two interfaces that extend set in Java are NavigableSet and SortedSet in the hierarchy.


Because the set is an interface, you cannot directly utilize the set to generate its object because it is an interface. To deal with it, you must utilize the four classes that implement the set interface: EnumSet, HashSet, LinkedHashSet, and TreeSet in Java.


What Operations Can You Perform on a Set in Java?

In Java, a set is a mathematical set on which you can perform operations such as union, intersection, and difference. You can accomplish this by using the addAll(), retainAll(), and removeAll() methods for the three operations shown above. The set's methods will be covered in detail later in this essay. But for now, consider what these operations do and how to perform them on the set. Consider the following two sets:


set1 = [3, 5, 9, 17, 23, 41] and set2 = [2, 5, 13, 17, 41, 51]. You can use these sets to execute the following tasks.


  • Union: After removing duplicate values, this operation will return the union of both sets1 and set2. As a result, the union of sets 1 and 2 yields [2, 3, 5, 9, 13, 17, 23, 41, 51].

  • Intersection: The intersection returns only the values shared by both sets—the intersection of sets 1 and 2 yields [5, 17, 41].


The first operand set values that are shared with the second operation set will be deleted by this operation. For example, the difference between sets 1 and 2 will be [3, 9, 23]. On the other hand, the difference between sets 2 and 1 is [2, 13, 51].


What Are the Different Setting Methods?

Java supports a wide range of methods. These methods can be used to conduct various operations on the set. All set interface methods are listed here, along with a description of their actions.


  • add(element)

Description: Adds a new value to the collection.


Example:


// Java code to illustrate add() method

import java.io.*;

import java.util.*;


public class TreeSetDemo {

public static void main(String args[])

{

// Creating an empty Set

Set<String> s = new HashSet<String>();


// Use add() method to add elements to the set

s.add("Welcome");

s.add("To");

s.add("Cipher");

s.add("Schools");

s.add("Java");

s.add("Program");


// Displaying the Set

System.out.println("The set is : " + s);

}

}


Output:

The set is: [Program, Schools, Cipher, Welcome, To]



  • addAll(collection)

Description: All the elements of a collection are added to the specified set.


Example:

import java.util.Collections;

import java.util.HashSet;

import java.util.Set;

public class CollectionsAddAllExample1 {

public static void main(String[] args) {

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

boolean b = Collections.addAll(set, 10, 20, 30, 40, 50);

System.out.println("Boolean Result: "+b);

System.out.println("Collection Value: "+set);

}

}


Output:

Boolean Result: true

Collection Value: [10, 20, 30, 40, 50]


  • clear()

Description: Clears all the values in a set (but not the set itself).


Example:

import java.util.Collection;

import java.util.concurrent.LinkedBlockingDeque;

public class JavaCollectionClearExample1 {

public static void main(String[] args) {

Collection<Integer> collection = new LinkedBlockingDeque<Integer>();

collection.add(99);

collection.add(190);

collection.add(287);

System.out.println("Collection : "+collection);

System.out.println("After applying clear() method here: ");

// clear() method will erase the whole collection

collection.clear();

System.out.println("Collection : "+collection);

}

}


Output:

Collection : [99, 190, 287]

After applying clear() method here:

Collection : []


  • contains(element)

Description: Determines whether the supplied element exists in a set.


Example:


// Java code to demonstrate the working of

// contains() method in List interface


import java.util.*;


class GFG {

public static void main(String[] args)

{

// creating an Empty Integer List

List<Integer> arr = new ArrayList<Integer>(4);


// using add() to initialize values

// [1, 2, 3, 4]

arr.add(1);

arr.add(2);

arr.add(3);

arr.add(4);


// use contains() to check if the element

// 2 exits or not

boolean ans = arr.contains(2);


if (ans)

System.out.println("The list contains 2 here");

else

System.out.println("The list does not contains 2 here");


// use contains() to check if the element

// 5 exits or not

ans = arr.contains(5);


if (ans)

System.out.println("The list contains 5 here");

else

System.out.println("The list does not contains 5 here");

}

}


Output:


The list contains 2 here

The list does not contains 5 here


  • containsAll(collection)

Description: Determines whether all of the values in a collection are present in a set.


Example:


// Java code to illustrate containsAll() method

import java.util.*;


public class ListDemo {

public static void main(String args[])

{

// Creating an empty list

List<String> list = new ArrayList<String>();


// Use add() method to add elements

// into the List

list.add("Welcome");

list.add("To");

list.add("Cipher");

list.add("Schools");

list.add("Program");


// Displaying the List

System.out.println("List: " + list);


// Creating another empty List

List<String> listTemp = new ArrayList<String>();


listTemp.add("Cipher");

listTemp.add("Schools");

listTemp.add("Program");


System.out.println("Are all the contents equal? "

+ list.containsAll(listTemp));

}

}


Output:


List: [Welcome, To, Cipher, Schools, Program]

Are all the contents equal? true


  • hashCode()

Description: Returns an integer hash code for a set instance.


Example:


public class IntegerHashCodeExample1 {

public static void main(String[] args)

{

//Create an integer object

Integer i = new Integer("102");

//Returned hash code value for this object

int hashValue = i.hashCode();

System.out.println("The Hash code Value for object is: " + hashValue);

}

}


Output:

The Hash code Value for object is: 102



  • isEmpty()

Description: Checks to see if the set is empty.


Example:


public class IsEmptyExample{

public static void main(String args[]){

String s1="";

String s2="CipherSchools";

System.out.println(s1.isEmpty());

System.out.println(s2.isEmpty());

}}


Output:

true

false


  • iterator()

Description: Returns an iterator object for traversing the set.


Example:


// Java program to Demonstrate Iterator


// Importing ArrayList and Iterator classes

// from Java.util package

import java.util.ArrayList;

import java.util.Iterator;


// Main class

public class Test {

// Main driver method

public static void main(String[] args)

{

// Creating an ArrayList class object

// Declaring object of integer type

ArrayList<Integer> al = new ArrayList<Integer>();


// Iterating over the List

for (int i = 0; i < 10; i++)

al.add(i);


// Printing the elements in the list

System.out.println(al);


// At the beginning itr(cursor) will point to

// index just before the first element in al

Iterator<Integer> itr = al.iterator();


// Checking the next element where

// condition holds till there is a single element

// in the List using hasnext() method

while (itr.hasNext()) {

// Moving the cursor to the next element

int i = itr.next();


// Getting elements one by one

System.out.print(i + " ");


// Removing odd elements

if (i % 2 != 0)

itr.remove();

}


// Command for next line

System.out.println();


// Printing the elements inside the object

System.out.println(al);

}

}


Output:

[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

0 1 2 3 4 5 6 7 8 9

[0, 2, 4, 6, 8]


  • remove(element)

Description: Removes a given value from the set.


Example:


// Java program to understand

// about vector.removeElement() function


// because the vector is present in this package

import java.util.*;


// Driver Code

public class vector_demo {

// main method begins here

public static void main(String[] args)

{

// creating vector type object

Vector<Integer> v

= new Vector<Integer>();


// inserting elements into the vector

v.add(1);

v.add(2);

v.add(3);

v.add(4);

v.add(5);

v.add(6);


// printing vector before deleting an element

System.out.println("Before deleting the vector");

System.out.println("Vector: " + v);

System.out.println("Size: " + v.size());


System.out.println("\nAfter deleting the vector");


// trying to delete object 3

boolean flag = v.removeElement(3);

if (flag) {

System.out.println("Element '3' has been removed");

}

else {

System.out.println("Element '3' is not present in Vector");

}


System.out.println("Vector: " + v);

System.out.println("Size: " + v.size());

}

}


Output:

Before deleting the vector

Vector: [1, 2, 3, 4, 5, 6]

Size: 6


After deleting the vector

Element '3' has been removed

Vector: [1, 2, 4, 5, 6]

Size: 5


  • removeAll(collection)

Description: To find the difference removes the components of a collection from the set.


Example:


// Java program to demonstrate

// removeAll() method for Integer value


import java.util.*;


public class CS {

public static void main(String[] argv) throws Exception

{

try {

// Creating object of ArrayList<Integer>

ArrayList<Integer> arrlist1 = new ArrayList<Integer>();


// Populating arrlist1

arrlist1.add(1);

arrlist1.add(2);

arrlist1.add(3);

arrlist1.add(4);

arrlist1.add(5);


// print arrlist1

System.out.println("ArrayList before "

+ "removeAll() operation : "

+ arrlist1);


// Creating another object of ArrayList<Integer>

ArrayList<Integer> arrlist2 = new ArrayList<Integer>();

arrlist2.add(1);

arrlist2.add(2);

arrlist2.add(3);


// print arrlist2

System.out.println("Collection Elements" + " to be removed : "+ arrlist2);


// Removing elements from arrlist

// specified in arrlist2

// using removeAll() method

arrlist1.removeAll(arrlist2);


// print arrlist1

System.out.println("ArrayList after "+ "removeAll() operation : " + arrlist1);

}


catch (NullPointerException e) {

System.out.println("Exception thrown : " + e);

}

}

}


Output:

ArrayList before removeAll() operation : [1, 2, 3, 4, 5]

Collection Elements to be removed : [1, 2, 3]

ArrayList after removeAll() operation : [4, 5]


  • retainAll(collection)

Description: The values of a collection in a set are retained.


Example:


// Java code to illustrate retainAll() method

import java.util.ArrayList;

public class CS {

public static void main(String[] args)

{

// Creating an empty array list

ArrayList<String> bags = new ArrayList<String>();


// Add values in the bags list.

bags.add("pen");

bags.add("pencil");

bags.add("paper");


// Creating another array list

ArrayList<String> boxes = new ArrayList<String>();


// Add values in the boxes list.

boxes.add("pen");

boxes.add("paper");

boxes.add("books");

boxes.add("rubber");


// Before Applying the method, print both lists

System.out.println("Bags Contains :" + bags);

System.out.println("Boxes Contains :" + boxes);


// Apply the retainAll() method to boxes passing bags as parameter

boxes.retainAll(bags);


// Displaying both lists after the operation

System.out.println("\nAfter Applying retainAll()"+

" method to Boxes\n");

System.out.println("Bags Contains :" + bags);

System.out.println("Boxes Contains :" + boxes);

}

}


Output:

Bags Contains :[pen, pencil, paper]

Boxes Contains :[pen, paper, books, rubber]

After Applying the retainAll() method to Boxes

Bags Contains :[pen, pencil, paper]

Boxes Contains :[pen, paper]



  • Returns the size of the set

Description: The size of the set is returned.


Example:

// Java code to illustrate set.size() method


import java.util.*;

public class SetDemo {

public static void main(String args[])

{

// Creating an empty Set

Set<String> set = new HashSet<String>();


// Use add() method to add elements to the set

set.add("Welcome");

set.add("To");

set.add("Cipher");

set.add("Schools");

set.add("Program");


// Displaying the Set

System.out.println("Set: " + set);


// Displaying the size of the set

System.out.println("The size of the set is: " + set.size());

}

}


Output:

Set: [Schools, Cipher, Welcome, To]

The size of the set is: 4


  • toArray()

Description: Makes an array from the elements of a set.


Example:


// Java Program to illustrate the

// ArrayList toArray() method in Java


import java.util.*;

public class CS {

public static void main(String[] args)

{

//Create object of ArrayList

ArrayList<Integer> ArrLis = new ArrayList<Integer>();


// Add elements

ArrLis.add(32);

ArrLis.add(67);

ArrLis.add(98);

ArrLis.add(100);


// print ArrayList

System.out.println("ArrayList: "

+ ArrLis);


// Get the array of the elements

// of the ArrayList

// using toArray() method

Object[] arr = ArrLis.toArray();


System.out.println("Elements of ArrayList"

+ " as Array: "

+ Arrays.toString(arr));

}

}


Output:

ArrayList: [32, 67, 98, 100]

Elements of ArrayList as Array: [32, 67, 98, 100]


Applications of using sets in Jav

Sets in Java are collections of unordered, unique elements. They are implemented using classes like HashSet, TreeSet, and LinkedHashSet. Sets are commonly used in Java for a variety of purposes, including:


Duplicate Element Removal: Sets automatically delete duplicate elements. This makes them handy when storing a collection of elements with no duplicates, such as deleting duplicate items from a list or locating unique pieces in a dataset.


Checking the Membership: Sets include efficient membership checking procedures, such as contains() and containsAll(), which can be used to determine whether an element is present in a collection. This is handy when rapidly determining whether an element is part of a collection, such as when looking for a certain element in a huge dataset.


Set Operations: Sets enable various set operations, such as union, intersection, and difference, which can be useful when combining or comparing sets of components. Sets can be used to locate similar elements between two collections, for example, or to combine many collections into a single set.


For Implementing Mathematical Concepts: Sets are frequently used to apply mathematical notions such as mathematical sets, Venn diagrams, and set theory operations. They can be used to represent sets of data elements and execute fundamental operations in set theory, such as union, intersection, and difference.


Deleting Elements: Sets contain methods to remove elements from the set, such as remove() and removeAll(), making them handy when modifying a collection by eliminating certain pieces.


Benefits of using sets in Java

Using sets in Java provides various advantages, including:

Sets Unique Elements: Sets automatically enforce element uniqueness, meaning no duplicate elements are allowed. This can be useful when you must keep a group of pieces without duplicates, preserving data integrity and consistency.


Efficient Membership Checking: Sets feature efficient membership checking procedures, such as contains() and contains (), which can quickly detect if an element is present in the set. This can be useful when rapidly checking if an element exists in a collection without iterating through the complete collection.


Set Operations: Sets provide a variety of set operations, such as union, intersection, and difference, which can be used to combine or compare sets of components. These efficient processes make sets suited for jobs involving set manipulation and comparison.


Memory Optimization and Performance: Sets are implemented using hash-based or tree-based data structures, which allow efficient lookup and insertion operations. This can result in speedier performance than alternative data structures, especially for huge datasets. Sets are also optimized for memory usage, making them memory efficient.


Simple Element Removal: Sets provide methods such as remove() and removeAll() to conveniently remove entries from the set. This can be handy when changing a collection by eliminating specific components while leaving the others alone.


Customizable Equality and Hashing: To determine equality and hash values, sets rely on the items' hashCode() and equals() methods. This enables the customization of equality tests and hash calculations for user-defined objects, making sets appropriate for cases where custom objects are used as elements or keys in maps.


Conclusion


Finally, sets are a useful collection type in Java that provides various advantages for organizing collections of unique components. Sets automatically guarantee uniqueness, facilitate set operations, optimize efficiency and memory usage, provide flexibility in implementations, allow for easy element removal, support customizable equality and hashing, and support iteration.


Sets in Java are a powerful tool that streamlines your code and enhances speed, whether you need to remove duplicates, conduct set operations, verify for membership, or manage collections of components efficiently. With their distinct properties and operations, sets provide a dependable and effective solution for a wide range of Java programming applications.


14 views

コメント


Subscribe to Our Newsletter

Thanks for submitting!

bottom of page