- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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
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) {}
- Related Articles
- Python Program to remove items from set
- Python Program to remove items from the set
- Java Program to remove all elements from a set in Java
- C++ Program to remove items from a given vector
- Golang program to remove all items from hash collection
- Remove duplicate items from an ArrayList in Java
- C# program to remove an item from Set
- Swift Program to Remove Null from a Set
- Swift Program to Remove an Element from the Set
- Swift Program to Remove a Subset from a Set
- Java Program to add and remove elements from a set which maintains the insertion order
- Swift Program to remove the first given number of items from the array
- Swift Program to remove the last given number of items from the array
- Golang Program To Remove The First Given Number Of Items From The Array
- Java Program to Remove elements from the LinkedList
