How to Convert Array to HashSet In Java

In this tutorial, i am going to explain how to convert given array to HashSet in java.

Problem: Consider an array

String[] strArr = {"abc","cde","def","efg","ghi"};

You need to convert it to HashSet.

Solutions:

1. Iterate the given array and store the values in a HashSet :

For iterating the array, use basic for loop or enhanced for loop. I am using enhanced for loop here. First create an empty HashSet and while iterating the for loop, insert the values into created HashSet object. Below is the code for this.
package com.speakingcs.collections;

import java.util.HashSet;

public class ArrayToSet {

 public static void main(String[] args) {
  
  String[] strArr = {"abc","cde","def","efg","ghi","hij"};
  
  // Set for storing values
  HashSet< String> strSet = new HashSet< String>();
  
  ArrayToSet as = new ArrayToSet();
  
  as.convertToSet(strArr,strSet);
  
  // printing the values to console.
  for(String str : strSet) {
   System.out.println(str);
  }

 }

 private void convertToSet(String[] strArr,HashSet< String> strSet) {

  // iterating the array and adding values to Set
  for(String str: strArr) {
   strSet.add(str);
  }
  
 }

}

2.Without Using for loop:

       Suppose, if you don't want to iterate the given array and just want to use any utility methods available, you can use overloaded constructor of HashSet. The code snippet is written below.

HashSet<String> strSet = new HashSet<String>(Arrays.asList(strArr)); 

3. Using Collections.addAll() method:

The Collections class has a convenient method for this purpose. The signature of Collections.addAll() method is like this.

public static <T> boolean addAll(Collection<? super T> c, T... elements) {
...
}

So to use this approach, first you need to create a HashSet Object, and then pass this object, as well as array to addAll() method. Below is code snippet.
String[] strArr = {"abc","cde","def","efg","ghi"};

HashSet<String> strSet = new HashSet<String>();

strSet = Collections.addAll(strSet,strArr);


Comments