Java TreeSet size() Example

The size() method of java.util.TreeSet class will return us the actual size of the TreeSet(Count of number of elements present in the TreeSet).

Signature

public int size()

This method returns number of elements in this TreeSet.

Example

The following example shows the usage of java.util.TreeSet.size() method.

import java.util.TreeSet;

public class SizeMethodTreeSetExample {
	public static void main(String args[])
	{
		// create an empty TreeSet
		TreeSet<String> treeSet1 = new TreeSet<String>();
		
		// use add() method to add elements to the TreeSet
		treeSet1.add("Element1");
		treeSet1.add("Element2");
		treeSet1.add("Element3");
		treeSet1.add("Element4");
		treeSet1.add("Element5");
		
		//Getting the size of the TreeSet
		System.out.println("Size of the TreeSet is : \""+treeSet1.size()+"\"");
			
		//Printing the elements of the TreeSet
		System.out.println("**Elements of the TreeSet **");
		for(String temp:treeSet1)
		{
			System.out.println(temp);
		}
	}
}

Output

Size of the TreeSet is : "5"
**Elements of the TreeSet**
Element1
Element2
Element3
Element4
Element5

Leave a Reply

Your email address will not be published. Required fields are marked *