» » » Basic Java program to Remove specified element from TreeSet example

1.Basic java example program to remove specified  element from treeset.

  1. package com.TreeSetExamplePrograms;

  2. public Class TreeSetRemoveDemo{ 
  3. import java.util.TreeSet;
  4.  
  5. public static void main(String args[]) {
  6. //create TreeSet object
  7.  
  8. TreeSet<Integer> treeSet = new TreeSet<Integer>();
  9.            
  10.    //add elements to TreeSet object
  11. treeSet.add(11);
  12. treeSet.add(12);
  13. treeSet.add(13);
  14.  
  15. System.out.println("TreeSet before removal : " + treeSet);
  16.            
  17.  /*
  18.  To remove an element from Java TreeSet object use,
  19.  boolean remove(Object o) method.
  20.  This method removes an element from TreeSet if it is present and returns
  21. true. Otherwise remove method returns false.
  22.  */
  23.            
  24.    boolean isRemoved = treeSet.remove(13);
  25.    System.out.println("Was 13 removed from TreeSet ? " + isRemoved);
  26.            
  27.   System.out.println("TreeSet elements after removal : " + treeSet);
  28.           
  29.  
  30. }
  31. }


Output:

  1. TreeSet before removal : [11, 12, 13]
  2. Was 13 removed from TreeSet ? true
  3. TreeSet elements after removal : [11, 12]


Remove all elements from Java TreeSet example:

1.Basic java example program to remove all elements from treeset.


  1. package com.TreeSetExamplePrograms;

  2. public Class TreeSetRemoveDemo{ 
  3. import java.util.TreeSet;
  4.  
  5. public static void main(String args[]) {
  6. //create TreeSet object
  7.  
  8. TreeSet<Integer> treeSet = new TreeSet<Integer>();
  9.            
  10.    //add elements to TreeSet object
  11. treeSet.add(11);
  12. treeSet.add(12);
  13. treeSet.add(13);
  14.  
  15. System.out.println("TreeSet before removal : " + treeSet);
  16.            
  17.  treeSet.clear();
  18. System.out.println("TreeSet after removal : " + treeSet);
  19.            
  20.  /*
  21.  To check whether TreeSet contains any elements or not use
  22.  boolean isEmpty() method.
  23.  isEmpty() method returns true if the TreeSet does not contains any elements
  24.  otherwise returns false.
  25.  */
  26.  
  27.  System.out.println("Is TreeSet empty ? " + treeSet.isEmpty());              
  28.  
  29. }
  30. }




Output:

  1. TreeSet before removal : [11, 12, 13]
  2. TreeSet after removal : []
  3. Is TreeSet empty ? true

Instance Of Java

We will help you in learning.Please leave your comments and suggestions in comment section. if you any doubts please use search box provided right side. Search there for answers thank you.
«
Next
Newer Post
»
Previous
Older Post

No comments

Leave a Reply

Select Menu