Remove Items from Set in Java



A set in Java is modelled after the mathematical set and it cannot contain duplicate elements. The set interface contains the methods that are inherited from Collection. The method remove() removes the specified items from the set collection.

A program that demonstrates the removal of items from Set using remove() is given as follows ?

Problem Statement

Given a Set, write a Java program to remove the elements from the Set ?

Input
[115, 20, 5, 70, 89, 10, 30, 111]
Output
[115, 20, 5, 70, 10, 30, 111]

Step to remove items from Set

Following are the step to remove items from Set ?

  • Define an array arr with elements.
  • Create a Set named set using HashSet.
  • Use a for loop to iterate over the array and add elements to the set using set.add(arr[i]).
  • Display the set using System.out.println(set).
  • Remove the element 89 from the set using set.remove(89).
  • Display the set again using System.out.println(set).

Java program to remove items from Set

import java.util.*;
public class Example {
 public static void main(String args[]) {
int arr[] = {5, 10, 10, 20, 30, 70, 89, 10, 111, 115};
Set<Integer> set = new HashSet<Integer>();
try {
 for(int i = 0; i < 10; i++) {
set.add(arr[i]);
 }
 System.out.println(set);
 set.remove(89);
 System.out.println(set);
}
catch(Exception e) {}
 }
}

Output

[115, 20, 5, 70, 89, 10, 30, 111]
[115, 20, 5, 70, 10, 30, 111]

Code explanation

Now let us understand the above program ?

The add() function is used to add elements to the set collection from array arr using a for loop. Then the set is displayed. The duplicate elements in the array are not available in the set as it cannot contain duplicate elements. The code snippet that demonstrates this is given as follows ?

int arr[] = {5, 10, 10, 20, 30, 70, 89, 10, 111, 115};
Set<Integer> set = new HashSet<Integer>();
try {
 for(int i = 0; i < 10; i++) {
set.add(arr[i]);
 }
System.out.println(set);

The element 89 is removed from the set using the remove() function. Then the set is again displayed. The code snippet that demonstrates this is given as follows ?

set.remove(89);
System.out.println(set);
}
catch(Exception e) {}
Updated on: 2024-07-31T17:51:18+05:30

3K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements