0% found this document useful (0 votes)
3 views

Convert a 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
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views

Convert a 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
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 2

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 com.mkyong;

import java.util.Arrays;

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 = Arrays.stream(lines.split("\\s+"))
.map(String::toUpperCase)
.toArray(String[]::new);

for (String s : result) {


System.out.println(s);
}

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


2.1 Stream to Integer[]

package com.mkyong;

import java.util.Arrays;

public class StreamInt1 {

public static void main(String[] args) {

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


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

System.out.println(Arrays.asList(result));

2.2 Stream to int[]

package com.mkyong;

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

public class StreamInt2 {

public static void main(String[] args) {

// IntStream -> int[]


int[] stream1 = IntStream.rangeClosed(1, 5).toArray();
System.out.println(Arrays.toString(stream1));

// Stream<Integer> -> int[]


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

System.out.println(Arrays.toString(result));

You might also like