Remove TreeSet elements

We can use remove() method of TreeSet to remove elements from TreeSet collection

boolean remove(Object obj)


Example

  1. import java.util.*;
  2. public class TreeSetRemoveExample {
  3. public static void main(String args[]) {
  4.  
  5. TreeSet<String> ts = new TreeSet<String>();
  6.  
  7. ts.add(“java”);
  8. ts.add(“c”);
  9. ts.add(“c++);
  10. System.out.println("TreeSet before removing elements”);
  11. System.out.println(ts);
  12. ts.remove(“java”);
  13. System.out.println("TreeSet after removing elements”);
  14. System.out.println(ts);
  15. }
  16. }
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

  1. import java.util.*;
  2. public class TreeSetRemoveAllExample {
  3. public static void main(String args[]) {
  4.  
  5. TreeSet<String> ts = new TreeSet<String>();
  6.  
  7. ts.add(“java”);
  8. ts.add(“c”);
  9. ts.add(“c++);
  10. System.out.println("TreeSet before removing all elements”);
  11. System.out.println(ts);
  12. ts.clear();
  13. System.out.println("TreeSet after removing all elements”);
  14. System.out.println(ts);
  15. }
  16. }
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);
}
}

About the Author

Karibasappa G C (KB)
Founder of javainsimpleway.com
I love Java and open source technologies and very much passionate about software development.
I like to share my knowledge with others especially on technology 🙂
I have given all the examples as simple as possible to understand for the beginners.
All the code posted on my blog is developed,compiled and tested in my development environment.
If you find any mistakes or bugs, Please drop an email to kb.knowledge.sharing@gmail.com

Connect with me on Facebook for more updates

Share this article on