
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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
OutputStream.of("Bing Bang Theory", "Vampire Diaries", "Game of Thrones", "Homecoming")
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 ?
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().
Advertisements