In Previous post we have learn how to convert Hashset to Array. In this post we will learn how to convert array to set . Array store data in contiguous memory locations and allow duplicate element to store. Set in java allow unique element only. Here we will discuss following ways for convert array to set in java.
Recommenced Post
- How to convert HashSet to Array
- How To Convert ArrayList To Array
- How to storing Java Object In HashSet
1. Using Arrays.asList() method
We will pass array as argument in hashset and it will create hashset from array with the help of Arrays.AsList() method.
import java.util.Arrays;
import java.util.HashSet;
public class ArrayToSet {
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("hashset is ="+ hashSet);
}
}
Output :
hashset is =[spring, java, android, php, angularjs]
2. Using Collections.AddAll() Method
Here , We will learn java program of convert array to set with help of collections.AddAll() method.
- Create an array to be convert
- Create an empty HashSet
- Add the element of array to hashset by passing array and hashset as argument in collections.AddAll() method .
import java.util.Collections;
import java.util.HashSet;
public class ArrayToSet2 {
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<String>();
//Adds all of the specified elements
//to the specified collection
Collections.addAll(hashSet, arr);
//print hashset
System.out.println("hashset is ="+ hashSet);
}
}
Output:
hashset is =[spring, java, android, php, angularjs]
3. Using Add() Method
In this method we will convert array to set by iterating element of array and one by one add to hashset using add() method .
import java.util.HashSet;
public class ArrayToSet2 {
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<String>();
for (String element : arr) {
hashSet.add(element);
}
//print hashset
System.out.println("hashset is ="+ hashSet);
}
}
Output :
hashset is =[spring, java, android, php, angularjs]
In this tutorial we have learn java program how to convert array to set in java. You can learn also how to convert HashSet to array
Reference :
A Guide To HashSet Java Doc – Hashset
This line seems to incorrect(asLIST):
Set hs = new HashSet(Arrays.asList(arr));