EN
Java 8 - convert Stream to Array
0 points
In this article, we would like to show you how to convert Stream to Array in Java 8.
Quick solution:
xxxxxxxxxx
1
// example stream
2
Stream<String> streamOfLetters = Stream.of("A", "B", "C");
3
4
// convert stream to array
5
String[] letters = streamOfLetters.toArray(String[]::new);
6
7
// display result
8
System.out.println(Arrays.toString(letters)); // [A, B, C]
In this example, we use Stream toArray() method to convert a stream of strings to the array.
xxxxxxxxxx
1
import java.util.Arrays;
2
import java.util.stream.Stream;
3
4
public class Example {
5
6
public static void main(String[] args) {
7
// example stream
8
Stream<String> streamOfLetters = Stream.of("A", "B", "C");
9
10
// convert stream to array
11
String[] letters = streamOfLetters.toArray(String[]::new);
12
13
// display result
14
System.out.println(Arrays.toString(letters)); // [A, B, C]
15
}
16
}
Output:
xxxxxxxxxx
1
[A, B, C]