[Java] How to convert an array into a set?
In Java, how to convert a given array of elements into a Set?
1 Answer
3 years ago by Eleven
We can convert the array to List using Arrays.asList
then we can create a Set from the List. Following code shows how to do that
import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;
public class JavaArrays {
public static void main(String[] args) {
String[] colors = { "red", "green", "blue", "orange", "maroon", "blue" };
Set<String> colorsSet = new HashSet<>(Arrays.asList(colors));
System.out.println(colorsSet);
}
}
Output:
[red, orange, green, blue, maroon]
Try code online here: https://onecompiler.com/java/3xmt7axc2
3 years ago by Karthik Divi