How to count number of element in TreeSet

import java.util.Set;
import java.util.TreeSet;

public class CountElement {

public static void main(String[] args) {

Set<String> ts = new TreeSet<String>();
ts.add(“mumbai”);
ts.add(“delhi”);
ts.add(“kolkata”);
ts.add(“chandigarh”);
ts.add(“dehradun”);

// print treeset
System.out.println(” ts =”+ts);

/*
* Returns the number of elements in this set (its
cardinality). If this set contains more than
Integer.MAX_VALUE elements, returns
Integer.MAX_VALUE.
*/

System.out.println(“Size of treeset = “+ts.size());

}

}

Output:

ts =[chandigarh, dehradun, delhi, kolkata, mumbai]

Size of treeset = 5

Related Posts:

Leave a Reply

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

2 + 2 =