How do I convert a Set to an Array in Java?
In Java, you can convert a Set to an array using the toArray method.
The syntax is: Set<Type> set = …; Type array = set. toArray new Type 0
This converts the elements of the Set into an array of the specified type.
To convert a Set to an Array in Java:
Method 1: Using toArray method
Set<String> set = new HashSet<>
set.add (“Apple”).
set.add (“Banana”)
set.add (“Cherry”)
String array = set.toArray (new String [0])
Method 2: Using Java 8 Stream API
Set<String> set = new HashSet<>();
set.add (“Apple”)
set.add (“Banana”)
set.add (“Cherry”)
String[] array = set.stream().toArray(String[]::new)
Method 3: Using Java 11+ toArray() method with generics
Set<String> set = new HashSet<>
set.add (“Apple”)
set.add (“Banana”)
set.add (“Cherry”)