0% found this document useful (0 votes)
4 views2 pages

Convert Java Stream to Array

The document explains how to convert a Stream to an Array in Java 8 using the .toArray() method. It provides examples for converting a Stream of Strings to a String array and converting IntStreams to both Integer arrays and int arrays. The code snippets illustrate the process of mapping and boxing elements before conversion.

Uploaded by

bavon mike
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views2 pages

Convert Java Stream to Array

The document explains how to convert a Stream to an Array in Java 8 using the .toArray() method. It provides examples for converting a Stream of Strings to a String array and converting IntStreams to both Integer arrays and int arrays. The code snippets illustrate the process of mapping and boxing elements before conversion.

Uploaded by

bavon mike
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Java 8 – Convert a Stream to Array

In Java 8, we can use .toArray() to convert a Stream into an Array.

1. Stream -> String[]


package [Link];

import [Link];

public class StreamString {

public static void main(String[] args) {

String lines = "I Love Java 8 Stream!";

// split by space, uppercase, and convert to Array


String[] result = [Link]([Link]("\\s+"))
.map(String::toUpperCase)
.toArray(String[]::new);

for (String s : result) {


[Link](s);
}

2. IntStream -> Integer[] or int[]


2.1 Stream to Integer[]

package [Link];

import [Link];

public class StreamInt1 {

public static void main(String[] args) {

int[] num = {1, 2, 3, 4, 5};


Integer[] result = [Link](num)
.map(x -> x * 2)
.boxed()
.toArray(Integer[]::new);

[Link]([Link](result));

2.2 Stream to int[]

package [Link];

import [Link];
import [Link];
import [Link];

public class StreamInt2 {

public static void main(String[] args) {

// IntStream -> int[]


int[] stream1 = [Link](1, 5).toArray();
[Link]([Link](stream1));

// Stream<Integer> -> int[]


Stream<Integer> stream2 = [Link](1, 2, 3, 4, 5);
int[] result = [Link](x -> x).toArray();

[Link]([Link](result));

You might also like