Convert Set to array in Java
This post will discuss how to convert a set to an array in plain Java, Java 8, and the Guava library.
1. Naive solution
A naive solution is to iterate over the given set and copy each encountered element in the Integer array one by one.
|
1 |
Set<Integer> set = new HashSet<>(Arrays.asList(1, 2, 3, 4, 5)); |
2. Using Set.toArray() method
Set interface provides the toArray() method that returns an Object array containing the elements of the set.
|
1 |
Set<Integer> set = new HashSet<>(Arrays.asList(1, 2, 3, 4, 5)); |
The JVM doesn’t know the desired object type, so the toArray() method returns an Object[]. We can pass a typed array to the overloaded toArray(T[] a) method to let JVM know your desired object type.
|
1 |
Set<Integer> set = new HashSet<>(Arrays.asList(1, 2, 3, 4, 5)); |
We can also pass an empty array of the specified type, and JVM will allocate the necessary memory:
|
1 |
Set<Integer> set = new HashSet<>(Arrays.asList(1, 2, 3, 4, 5)); |
3. Using Java 8
In Java 8, we can use the Stream to convert a set to an array. The idea is to convert a given set to stream using Set.stream() method and use Stream.toArray() method to return an array containing the stream elements. There are two ways to do so:
⮚ Using Streams with method reference
|
1 |
Set<Integer> set = new HashSet<>(Arrays.asList(1, 2, 3, 4, 5)); |
⮚ Using Streams with lambda expression
|
1 |
Set<Integer> set = new HashSet<>(Arrays.asList(1, 2, 3, 4, 5)); |
4. Using Guava Library
⮚ Using FluentIterable class:
The FluentIterable is an expanded Iterable API that provides similar functionality as Java 8’s Stream. We can get a fluent iterable that wraps an iterable set and returns an array containing all the elements from the fluent iterable.
|
1 |
Set<Integer> set = new HashSet<>(Arrays.asList(1, 2, 3, 4, 5)); |
⮚ Using Iterables class:
Guava’s Iterables class also provides the toArray() method that copies an iterable’s elements into an array.
|
1 |
Set<Integer> set = new HashSet<>(Arrays.asList(1, 2, 3, 4, 5)); |
That’s all about converting Set to array in Java.
原创文章,作者:carmelaweatherly,如若转载,请注明出处:https://blog.ytso.com/tech/pnotes/273619.html