HashSet Example in Java

  • HashSet extends AbstractSet and implements the Set interface.
  • HashSet does not hold any duplicate elements, contains only unique elements.
  • HashSet is non-synchronized.
  • HashSet doesn't maintain any order like HashMap.
  • Iterator returned by HashSet is fail-fast Iterator, it will throw ConcurrentModificationException if iterator is modified after it's creation.

In this example we will demonstrate mostly used methods of HashSet.

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

public class HashSetExample {
	public static void main(String[] args) {
		// Creating a HasSet to add strings
		HashSet<String> myHashSet = new HashSet<String>();
		myHashSet.add("Element1");
		myHashSet.add("Element2");
		myHashSet.add("Element3");
		myHashSet.add("Element4");

		// Printing the elements it contains
		System.out.println(myHashSet);

		// Iterating each element of myHashSet using Iterator
		Iterator<String> iterator = myHashSet.iterator();
		while (iterator.hasNext()) {
			System.out.println(iterator.next());
		}

		// contains method check whether the set contains the specified element
		// or not
		System.out.println(myHashSet.contains("Element1")); // true
		System.out.println(myHashSet.contains("Element5"));// false

		// Print the size of the set
		System.out.println("size: " + myHashSet.size());

		// Remove an element from the set
		myHashSet.remove("Element1");

		System.out.println("After removing Element1 : " + myHashSet);

		// Removes all of the elements from this set
		myHashSet.clear();
		System.out.println("After calling clear() : " + myHashSet);
		
		//isEmpty() Returns true if the set contains no elements
		System.out.println("is empty :"+myHashSet.isEmpty());
	}
}
Output
[Element1, Element2, Element3, Element4] Element1 Element2 Element3 Element4 true false size: 4 After removing Element1 : [Element2, Element3, Element4] After calling clear() : [] is empty :true












Related Examples


Write a program to check if an input String is Palindrome or not?
Calculate the factorial of a given number using Java?
How to reverse a number in Java?
Write a program to convert from decimal to binary?
Producer Consumer Example in Thread
Write a program to reverse a String?








Receive Latest Java Examples in Your Email: