Signup/Sign In

How to Convert Array to Set in Java

In this post, we are going to convert an array to set by using Java co de. An Array is an index based data structure that is used to store similar types of data while the set is a collection of unique elements.

Here, we have several examples to convert an array to set, always remember that set contains unique elements only so duplicate elements of the array will not add to the set during conversion.

Here, we used addAll(), asList() and toSet() methods to get set from array elements. The addAll() method is a Collections class method that adds array elements to the specified collection(list, set, etc)

Time for an Example

Let's take an example to convert an array to Set. Here, we used addAll() method to add elements into the set. This is pretty easy to get set from an array.

import java.util.Collections;
import java.util.HashSet;
import java.util.Set;
public class Main {
	public static void main(String[] args){
		String[] fruits = {"Apple", "Orange", "Banana","Orange"};
		for (int i = 0; i < fruits.length; i++) {
			System.out.println(fruits[i]);
		}
		Set<String> fruitsSet = new HashSet<>();
		Collections.addAll(fruitsSet, fruits);
		System.out.println(fruitsSet);	
	}
}


Apple
Orange
Banana
Orange
[Apple, Orange, Banana]

Example:

We can use asList() method to get convert array to set. The asList() method returns a list of the array that further is converted by the constructor to a set. See the below example.

import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;
public class Main {
	public static void main(String[] args){
		String[] fruits = {"Apple", "Orange", "Banana","Orange"};
		for (int i = 0; i < fruits.length; i++) {
			System.out.println(fruits[i]);
		}
		Set<String> fruitsSet = new HashSet<>(Arrays.asList(fruits));
		System.out.println(fruitsSet);	
	}
}


Apple
Orange
Banana
Orange
[Apple, Orange, Banana]

Example: Java 8

Let's create another example to get set from array elements. Here, we are using the toSet() method of Collectors class that returns set from the stream elements. This example is useful if you want to use the stream to get set elements.

import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;
import java.util.stream.Collectors;
public class Main {
	public static void main(String[] args){
		String[] fruits = {"Apple", "Orange", "Banana","Orange"};
		for (int i = 0; i < fruits.length; i++) {
			System.out.println(fruits[i]);
		}
		Set<String> fruitsSet = new HashSet<>();
		fruitsSet = Arrays.stream(fruits).collect(Collectors.toSet());
		System.out.println(fruitsSet);	
	}
}


Apple
Orange
Banana
Orange
[Apple, Orange, Banana]



About the author:
I am a 3rd-year Computer Science Engineering student at Vellore Institute of Technology. I like to play around with new technologies and love to code.