What is the best way to convert an array to a Set in Java?
I have an array in Java, and I need to convert it into a Set
. Of course, I could use a loop to manually add elements, but I’m looking for a cleaner and more efficient way.
I came across java.util.Arrays.asList(Object[] a)
, but that gives me a List
, not a Set
.
How can I properly convert a Java array to a Set while maintaining uniqueness and efficiency?
If you’re just getting started and want a simple way to convert a java array to set
, using HashSet
with Arrays.asList()
is a straightforward option.
import java.util.*;
public class Main {
public static void main(String[] args) {
String[] array = {"apple", "banana", "orange", "apple"};
Set<String> set = new HashSet<>(Arrays.asList(array));
System.out.println(set); // Output: [banana, orange, apple]
}
}
Why this works:
Arrays.asList()creates a
Listfrom the array, and wrapping it in a
HashSetensures uniqueness. This is a quick and easy way to convert a
java array to set`.
That’s a good approach, But if you’re using Java 8 or above, you can take advantage of Streams for a cleaner, more efficient solution. It handles large datasets better too.
import java.util.*;
import java.util.stream.*;
public class Main {
public static void main(String[] args) {
String[] array = {"apple", "banana", "orange", "apple"};
Set<String> set = Arrays.stream(array).collect(Collectors.toSet());
System.out.println(set); // Output: [banana, orange, apple]
}
}
Why this is great:
The Stream
API makes the code concise and handles operations on large datasets efficiently. It’s a modern way to convert a java array to set
.
Nice one, @kumari_babitaa Here’s another trick if you prefer working with the Collections
utility class. You can populate a Set
directly with Collections.addAll()
—no need to convert the array to a List
first."
import java.util.*;
public class Main {
public static void main(String[] args) {
String[] array = {"apple", "banana", "orange", "apple"};
Set<String> set = new HashSet<>();
Collections.addAll(set, array);
System.out.println(set); // Output: [banana, orange, apple]
}
}
Why this is useful:
It’s direct, efficient, and avoids unnecessary conversions. Another handy way to convert a java array to set
.