How Java 8 Converts Array to Stream

Introduction

In Java 8, you can use Array. Stream or Stream.of to convert Array to Stream.

1. Object array

For object arrays, both Arrays.stream and Stream.of return the same output.

public static void main(String[] args) {

    ObjectArrays();
  }

  private static void ObjectArrays() {
    String[] array = {"a", "b", "c", "d", "e"};
    //Arrays.stream
    Stream<String> stream = Arrays.stream(array);
    stream.forEach(x-> System.out.println(x));

    System.out.println("======");

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

Output:

a
b
c
d
e
======
a
b
c
d
e

Looking at the JDK source code, Stream.of internally calls the Arrays.stream method for an array of objects.

// Arrays
public static <T> Stream<T> stream(T[] array) {
    return stream(array, 0, array.length);
}

// Stream
public static<T> Stream<T> of(T... values) {
    return Arrays.stream(values);
}

2. Basic arrays

For basic arrays, Arrays.stream and Stream.of will return different outputs.

public static void main(String[] args) {

    PrimitiveArrays();
  }

private static void PrimitiveArrays() {
    int[] intArray = {1, 2, 3, 4, 5};

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

    System.out.println("======");

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

    // Can't output directly, need to convert to IntStream first
    IntStream intStream = temp.flatMapToInt(x -> Arrays.stream(x));
    intStream.forEach(x-> System.out.println(x));

  }

Output:

1
2
3
4
5
======
1
2
3
4
5

Look at the source code.

// Arrays
public static IntStream stream(int[] array) {
    return stream(array, 0, array.length);
}

// Stream
public static<T> Stream<T> of(T t) {
    return StreamSupport.stream(new Streams.StreamBuilderImpl<>(t), false);
}

Which one

  • For object arrays, both call the same Arrays.stream method
  • For basic arrays, I prefer Arrays.stream because it returns a fixed size IntStream and is easier to manipulate.

Therefore, it is recommended to use Arrays.stream, without considering whether it is an object array or a basic array, to return the corresponding stream object directly, which is easy to operate.

See: java-8-demo

For more details, see: Java 8 Tutorial

Tags: Java JDK

Posted on Sun, 06 Oct 2019 10:20:12 -0700 by m4x3vo