How to create Hashset In Java

In previous tutorials we have learn about hashset java and its basic things like hashset syntax in java , hashset declaration in java and java hashset methods. If you are new in hashset i recommended read this tutorial java hashset example . In this post we will see hashset example for how to create hashset in java and  initialize hashset in java. We can create hashset in java using constructor we have four type constructor of hashset in java , Let’s see how to create hashset in java by code

HashSet<String> hashSet = new HashSet<>();
HashSet<String> hashSet = new HashSet<>(5);
HashSet<String> hashSet = new HashSet<>(5,9);
HashSet<String> hashSet = new HashSet<>(set);

Initialize hashset In java

We can initialize hashset in java with belows ways

  1. Using Constructor – We can pass collection in hashset constructor , java initialize hashset with values of given collection.
import java.util.Arrays;
import java.util.HashSet;

public class HashSetCreate {
           public static void main(String[] args) {
        	String [] arr = {"java","php","android","angularjs","spring"};   
 
            //Constructs a new set containing the 
        	//elements in the specified collection
        	HashSet<String> hashSet = new HashSet<>(Arrays.asList(arr));
			
			//print hashset
		   System.out.println("element of hahset ="+ hashSet);
			
		}
}

Output :

element of hahset =[spring, java, android, php, angularjs]

2. Using add() Method – In this  way we will add element in hashset using aadd() method

import java.util.HashSet;

public class HashSetAdd {
	public static void main(String[] args) {
		
		//Constructs a new, empty set
	   HashSet<String>	hashSet = new HashSet<String>();
	   
	   //add element in it 
	   hashSet.add("java");
	   hashSet.add("php");
	   hashSet.add("android");
	   
	   //display the element 
	   System.out.println("element in hashset ="+ hashSet);
	   
	}
}

Output :

element in hashset =[java, android, php]

Reference :

A Guide To HashSet

Java Doc – HashSet

 

Leave a Reply

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

5 + 4 =