Get Size of TreeSet in Java

Java 8Object Oriented ProgrammingProgramming

To get the size of TreeSet, use the size() method.

Create a TreeSet and add elements to it −

TreeSet<String> tSet = new TreeSet<String>();
tSet.add("78");
tSet.add("56");
tSet.add("88");
tSet.add("12");

Now, get the size of the TreeSet −

tSet.size()

The following is an example to get the size of TreeSet in Java −

Example

 Live Demo

import java.util.*;
public class Demo {
   public static void main(String args[]){
      TreeSet<String> tSet = new TreeSet<String>();
      tSet.add("78");
      tSet.add("56");
      tSet.add("88");
      tSet.add("12");
      System.out.println("TreeSet elements...");
      Iterator<String> i = tSet.iterator();
      while(i.hasNext()){
         System.out.println(i.next());
      }
      System.out.println("Size of TreeSet = " + tSet.size());
      System.out.println("Removing Highest Value = "+tSet.pollLast());
      System.out.println("\nUpdated TreeSet elements...");
      i = tSet.iterator();
      while(i.hasNext()){
         System.out.println(i.next());
      }
      System.out.println("Size of TreeSet after removing an element = " + tSet.size());
   }
}

Output

TreeSet elements...
12
56
78
88
Size of TreeSet = 4
Removing Highest Value = 88

Updated TreeSet elements...
12
56
78
Size of TreeSet after removing an element = 3
raja
Published on 11-Jan-2019 11:01:30
Advertisements