Java - HashSet example

Posted on October 23, 2016


This tutorial shows how we can perform various operations on the HashSet like

  • Adding an element into the HashSet .
  • Removing an element from the HashSet .
  • Printing the size of the HashSet .
  • Checking if an element exists in the HashSet or not.
  • Removing all elements from the HashSet .

HashSetExample.java

package com.boraji.tutorial;

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

/**
 * @author imssbora
 *
 */
public class HashSetExample {
	public static void main(String[] args) {
		Set<String> set=new HashSet<>();
		
		/*Adding elements into set*/
		set.add("A");
		set.add("B");
		set.add("C");
		set.add("D");
		set.add("E");
		
		System.out.println("Set elements:"+set);
		
		/*Removing an element from set*/
		set.remove("A");
		System.out.println("Set elements after removal:"+set);
		
		/*Printing the size of set*/
		System.out.println("Set size:"+set.size());
		
		/*Checking if an elements exist in set or not*/
		System.out.println("Element 'D' exist in set:"+set.contains("D"));
		
		/*Removing all elements from set*/
		set.clear();
		System.out.println("Elements in set:"+set);
		
	}
}

Output

Set elements:[A, B, C, D, E]
Set elements after removal:[B, C, D, E]
Set size:4
Element 'D' exist in set:true
Elements in set:[]