The java.util.Set.remove(Object o) method is used to remove a specific element from a Set. It returns true if the element was present and successfully removed, otherwise, it returns false. This works for all types of sets (HashSet, TreeSet, LinkedHashSet) and is useful for removing elements without iterating the entire set.
Example:
import java.util.*;
public class SetRemoveExample {
public static void main(String[] args) {
Set<String> set = new HashSet<>();
set.add("Apple");
set.add("Banana");
set.add("Orange");
System.out.println("Original Set: " + set);
set.remove("Banana");
System.out.println("Set after removing 'Banana': " + set);
}
}
Output
Original Set: [Apple, Orange, Banana] Set after removing 'Banana': [Apple, Orange]
Explanation:
- Set<String> set = new HashSet<>(): creates a hashSet and elements are added using add().
- remove("Banana") deletes "Banana" from the set.
Syntax
boolean remove(Object o)
- Parameters: "o" the element to be removed from the set.
- Return Value: true if the element was present and removed and false if the element was not found in the set.
Example: This code shows how to remove elements from a HashSet using Set.remove(), where duplicates are ignored and order is not maintained.
import java.util.*;
public class SetDemo {
public static void main(String[] args) {
Set<String> set = new HashSet<>();
set.add("Welcome");
set.add("To");
set.add("Geeks");
set.add("4");
set.add("Geeks");
System.out.println("Original Set: " + set);
set.remove("Geeks");
set.remove("4");
set.remove("Welcome");
System.out.println("Set after removing elements: " + set);
}
}
Output
Original Set: [4, Geeks, Welcome, To] Set after removing elements: [To]
Explanation:
- Set<String> set = new HashSet<>(): creates a hashSet and elements are added using add().
- Duplicate elements like "Geeks" are automatically ignored.
- The remove() method is used to delete "Geeks", "4", and "Welcome" from the set.