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:
- Java – How to get size or length of HashSet ?
- Java – How to delete a element and delete all elements of HashSet ?
- Java – retainAll() method explanation with HashSet
- Java – How to check whether particular element is present in HashSet ?
- Java – Comparing two HashSet objects using containsAll() method
- Java – Adding one HashSet to another HashSet using addAll() method
- Java – Various ways to iterate through HashSet
- Java – How to reverse LinkedHashSet contents ?
- Java – Sorting HashSet contents in ascending and descending order
- Java – How to Sort HashSet in 2 ways ?
References:
- https://docs.oracle.com/javase/tutorial/collections/intro/
- https://docs.oracle.com/javase/tutorial/collections/interfaces/collection.html
- https://docs.oracle.com/javase/7/docs/api/java/util/Collection.html
- https://docs.oracle.com/javase/tutorial/collections/interfaces/set.html
- https://docs.oracle.com/javase/7/docs/api/java/util/Set.html
- https://docs.oracle.com/javase/7/docs/api/java/util/class-use/HashSet.html
- https://docs.oracle.com/javase/7/docs/api/java/util/HashSet.html
- https://docs.oracle.com/javase/8/docs/api/java/util/Iterator.html
Happy Coding !!
Happy Learning !!