Java program to remove items from Set


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 −

Example

 Live Demo

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]

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) {}

karthikeya Boyini
karthikeya Boyini

I love programming (: That's all I know

Updated on: 26-Jun-2020

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements