Java – How to get size or length of HashSet ?

In this article, we will discuss how to find size or length of HashSet

1. HashSet :

We can use, size() method of Collection interface to find size of an HashSet which

  • stores only unique elements
  • allows maximum of one null element
  • stores elements in random-order

2. To get size of HashSet using size() method :

FindSizeOfHashSet.java

package in.bench.resources.java.collections;

import java.util.HashSet;
import java.util.Iterator;

public class FindSizeOfHashSet {

	public static void main(String[] args) {

		// creating HashSet object of type String
		HashSet<String> hs = new HashSet<String>();

		// adding elements to HashSet object
		hs.add("Sundar Pichai");
		hs.add("Satya Nadella");
		hs.add("Shiv Nadar");
		hs.add("Shantanu Narayen");
		hs.add("Sundar Pichai"); // duplicate object
		hs.add("Francisco D’Souza");
		hs.add(null); // one null is allowed
		hs.add(null); // Again, null is allowed - duplicate

		int hashSetSize = hs.size();

		System.out.println("Size of an HashSet is : " + hashSetSize);

		// Iterating using Iterator of Collection interface
		System.out.println("\n\nIterating HashSet elements\n");
		Iterator<String> itr = hs.iterator();
		while(itr.hasNext()) {
			System.out.println(itr.next());
		}
	}
}

Output:

Size of an HashSet is : 6

Iterating HashSet elements

null
Shantanu Narayen
Shiv Nadar
Sundar Pichai
Satya Nadella
Francisco D’Souza

From above example, HashSet

  • doesn’t allow duplicate elements
  • maximum of one null object is allowed
  • while iterating, retrieve elements in random-order

Related Articles:

References:

Happy Coding !!
Happy Learning !!

Java - How to delete an element and delete all elements of HashSet ?
Java - Conversion of Arrays to Vector