TreeSet size() method in java

Let’s learn TreeSet size() method in java.

TreeSet size() method in java

size() method of TreeSet class returns the number of elements in this set (its cardinality).

Syntax:

public int size()

Now let’s see example on TreeSet size() method.

import java.util.TreeSet;
public class TreeSetSizeMethodExample
{
   public static void main(String[] args)
   {
      TreeSet<String> ts = new TreeSet<String>();
      ts.add("watermelon");
      ts.add("apple");
      ts.add("banana");
      ts.add("grapes");
      ts.add("mango");
      ts.add("orange");
      System.out.println("Given TreeSet: " + ts);
      // print size of TreeSet
      System.out.println("size of TreeSet is: " + ts.size());
   }
}


Output:

Given TreeSet: [apple, banana, grapes, mango, orange, watermelon]
size of TreeSet is: 6


Also read – multidimensional array in java