How to count number of element in HashSet

In order to count number of element in Set/HashSet , use size() method. Set.size() method returns the number of elements in this set (its cardinality).

Syntax :

public int size() {
   }

Parameter : It does not take any parameter.                                                                              Returns Value : It the number of elements in this set (its cardinality)


import java.util.HashSet;
import java.util.Set;

public class CountElement {

public static void main(String[] args) {

Set<String> hs = new HashSet<String>();
hs.add("java");
hs.add("php");
hs.add("html");
hs.add("javascript");
hs.add("mysql");

//print hashset
System.out.println("hashset = "+hs);

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

System.out.println("Size of hashset = "+hs.size());
}

}

Output:

hashset = [javascript, php, html, java, mysql]

Size of hashset = 5

A Guide To HashSet

Java Doc – HashSet

Leave a Reply

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

3 + 7 =