AddThis

Thursday, 21 June 2018

How to convert Array to Stream in Java?

In Java 8, you can either use Arrays.stream or Stream.of to convert an Array into a Stream.

1. Object Arrays

For object arrays, both Arrays.stream and Stream.of returns the same output.
TestJava8.java
package com.mkyong.java8;

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

public class TestJava8 {

    public static void main(String[] args) {

        String[] array = {"a", "b", "c", "d", "e"};

        //Arrays.stream
        Stream<String> stream1 = Arrays.stream(array);
        stream1.forEach(x -> System.out.println(x));

        //Stream.of
        Stream<String> stream2 = Stream.of(array);
        stream2.forEach(x -> System.out.println(x));
    }

}

Note
For object arrays, the Stream.of method is calling the Arrays.stream internally.

2. Primitive Arrays

For primitive array, the Arrays.stream and Stream.of will return different output.
TestJava8.java
package com.mkyong.java8;

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

public class TestJava8 {

    public static void main(String[] args) {

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

        // 1. Arrays.stream -> IntStream 
        IntStream intStream1 = Arrays.stream(intArray);
        intStream1.forEach(x -> System.out.println(x));

        // 2. Stream.of -> Stream<int[]>
        Stream<int[]> temp = Stream.of(intArray);

        // Cant print Stream<int[]> directly, convert / flat it to IntStream 
        IntStream intStream2 = temp.flatMapToInt(x -> Arrays.stream(x));
        intStream2.forEach(x -> System.out.println(x));

    }

}

Which one?
For object arrays, both are calling the same Arrays.stream (refer example 1, JDK source code). For primitive arrays, I prefer Arrays.stream as well, because it returns fixed size IntStream directly, easier to manipulate it.

No comments:

Post a Comment

Solving real time queries using java 8 features stream api with examples

package com.pse; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.Comparator; import java...