Remove specified element from TreeSet in Java

Java 8Object Oriented ProgrammingProgramming

Use the remove() method to remove specified elements from TreeSet.

At first, create a TreeSet and add elements −

TreeSet<String> set = new TreeSet<String>();
set.add("34");
set.add("12");
set.add("67");
set.add("54");
set.add("76");
set.add("49");

Now, remove the specified element i.e. 34 here −

set.remove("34")

The following is an example to remove specified element from TreeSet −

Example

 Live Demo

import java.util.*;
public class Demo {
   public static void main(String args[]){
      TreeSet<String> set = new TreeSet<String>();
      set.add("34");
      set.add("12");
      set.add("67");
      set.add("54");
      set.add("76");
      set.add("49");
      System.out.println("TreeSet elements...");
      Iterator<String> i = set.iterator();
      while(i.hasNext()) {
         System.out.println(i.next());
      }
      System.out.println("Removed element 34 from the TreeSet ? " + set.remove("34"));
      System.out.println("Updated TreeSet elements...");
      i = set.iterator();
      while(i.hasNext()) {
         System.out.println(i.next());
      }
   }
}

Output

TreeSet elements...
12
34
49
54
67
76
Removed element 34 from the TreeSet ? true
Updated TreeSet elements...
12
49
54
67
76
raja
Published on 11-Jan-2019 06:55:58
Advertisements