How to Convert a Java 8 Stream to an Array?

将Java 8 Stream转换为数组最简单/最简单的方法是什么?


The easiest method is to use the toArray(IntFunction<A[]> generator) method with an array constructor reference. This is suggested in the API documentation for the method.

String[] stringArray = streamString.toArray(String[]::new);

What it does, is find a method that takes in an integer (the size) as argument, and returns a String[] , which is exactly what (one of the overloads of) new String[] does.

You could also write your own IntFunction :

Stream<String> stream = ...;
String[] stringArray = stream.toArray(size -> new String[size]);

The purpose of the IntFunction<A[]> generator is to convert an integer, the size of the array, to a new array.

Example code:

Stream<String> streamString = Stream.of("a", "b", "c");
String[] stringArray = streamString.toArray(size -> new String[size]);
Arrays.stream(stringArray).forEach(System.out::println);

Prints:

a
b
c

If you want to get an array of ints, with values form 1 to 10, from a Stream, there is IntStream at your disposal.

Here we create a Stream with a Stream.of method and convert an Stream to an IntStream using a mapToInt. Then we can call IntStream's toArray method.

Stream<Integer> stream = Stream.of(1,2,3,4,5,6,7,8,9,10);
//or use this to create our stream 
//Stream<Integer> stream = IntStream.rangeClosed(1, 10).boxed();
int[] array =  stream.mapToInt(x -> x).toArray();

Here is the same thing, without the Stream, using only the IntStream

int[]array2 =  IntStream.rangeClosed(1, 10).toArray();

You can convert a java 8 stream to an array using this simple code block:

 String[] myNewArray3 = myNewStream.toArray(String[]::new);

But let's explain things more, first, let's Create a list of string filled with three values:

String[] stringList = {"Bachiri","Taoufiq","Abderrahman"};

Create a stream from the given Array :

Stream<String> stringStream = Arrays.stream(stringList);

we can now perform some operations on this stream Ex:

Stream<String> myNewStream = stringStream.map(s -> s.toUpperCase());

and finally convert it to a java 8 Array using these methods:

1-Classic method (Functional interface)

IntFunction<String[]> intFunction = new IntFunction<String[]>() {
    @Override
    public String[] apply(int value) {
        return new String[value];
    }
};


String[] myNewArray = myNewStream.toArray(intFunction);

2 -Lambda expression

 String[] myNewArray2 = myNewStream.toArray(value -> new String[value]);

3- Method reference

String[] myNewArray3 = myNewStream.toArray(String[]::new);

Method reference Explanation:

It's another way of writing a lambda expression that it's strictly equivalent to the other.

链接地址: http://www.djcxy.com/p/91904.html

上一篇: 为什么C ++没有反射?

下一篇: 如何将Java 8流转换为数组?