Convert Stream to Typed Array in Java



In this article, we will learn how to change a Java Stream into a typed array in Java. By using the toArray() method with a constructor reference, we can ensure that the array has the right type.

Problem Statement

Given a Stream of strings, write a Java program to convert it into a typed array and display the elements.
Input
Stream.of("Bing Bang Theory", "Vampire Diaries", "Game of Thrones", "Homecoming")
Output
Array...Bing Bang TheoryVampire DiariesGame of ThronesHomecoming

Steps to convert the stream to a typed array

The following are the steps to covert the stream to a typed array ?

  • Imports the necessary classes from java.util and java.util.stream packages
  • Create a Stream of strings.
  • Convert the Stream to a typed array using toArray().
  • Return the array elements.

Java program to convert the stream to a typed array

The following is an example of converting the stream to a typed array ?

Open Compiler
import java.util.Arrays; import java.util.stream.Stream; public class Demo { public static void main(String[] args) { Stream<String> stream = Stream.of("Bing Bang Theory", "Vampire Diaries", "Game of Thrones", "Homecoming"); final String[] strArr = stream.toArray(String[]::new); System.out.println("Array..."); Arrays.asList(strArr).forEach(n-> System.out.println(n)); } }

Output

Array...
Bing Bang Theory
Vampire Diaries
Game of Thrones
Homecoming

Code Explanation

The Stream is created with Stream.of(). The toArray() method converts the Stream to a String[] using String[]::new to specify the array type. The array elements are then printed using forEach().

Updated on: 2024-11-15T18:45:03+05:30

311 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements