Languages
[Edit]
EN

Java 8 - convert Stream to Array

0 points
Created by:
Flimzy
356

In this article, we would like to show you how to convert Stream to Array in Java 8.

Quick solution:

// example stream
Stream<String> streamOfLetters = Stream.of("A", "B", "C");

// convert stream to array
String[] letters = streamOfLetters.toArray(String[]::new);

// display result
System.out.println(Arrays.toString(letters));  // [A, B, C]

 

Practical example

In this example, we use Stream toArray() method to convert a stream of strings to the array.

import java.util.Arrays;
import java.util.stream.Stream;

public class Example {

    public static void main(String[] args) {
        // example stream
        Stream<String> streamOfLetters = Stream.of("A", "B", "C");

        // convert stream to array
        String[] letters = streamOfLetters.toArray(String[]::new);

        // display result
        System.out.println(Arrays.toString(letters));  // [A, B, C]
    }
}

Output:

[A, B, C]

References

Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join