Remove TreeSet elements
We can use remove() method of TreeSet to remove elements from TreeSet collection
boolean remove(Object obj)
Example
- import java.util.*;
- public class TreeSetRemoveExample {
- public static void main(String args[]) {
- TreeSet<String> ts = new TreeSet<String>();
- ts.add(“java”);
- ts.add(“c”);
- ts.add(“c++”);
- System.out.println("TreeSet before removing elements”);
- System.out.println(ts);
- ts.remove(“java”);
- System.out.println("TreeSet after removing elements”);
- System.out.println(ts);
- }
- }
import java.util.*; public class TreeSetRemoveExample { public static void main(String args[]) { TreeSet<String> ts = new TreeSet<String>(); ts.add(“java”); ts.add(“c”); ts.add(“c++”); System.out.println("TreeSet before removing elements”); System.out.println(ts); ts.remove(“java”); System.out.println("TreeSet after removing elements”); System.out.println(ts); } }
Removing all elements at once
We can use clear() method of TreeSet to remove all elements in one go
Example
- import java.util.*;
- public class TreeSetRemoveAllExample {
- public static void main(String args[]) {
- TreeSet<String> ts = new TreeSet<String>();
- ts.add(“java”);
- ts.add(“c”);
- ts.add(“c++”);
- System.out.println("TreeSet before removing all elements”);
- System.out.println(ts);
- ts.clear();
- System.out.println("TreeSet after removing all elements”);
- System.out.println(ts);
- }
- }
import java.util.*; public class TreeSetRemoveAllExample { public static void main(String args[]) { TreeSet<String> ts = new TreeSet<String>(); ts.add(“java”); ts.add(“c”); ts.add(“c++”); System.out.println("TreeSet before removing all elements”); System.out.println(ts); ts.clear(); System.out.println("TreeSet after removing all elements”); System.out.println(ts); } }