本文介绍了如何转换一个Java 8个流到数组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

什么是转换一个Java 8的最简单/最短路径到一个数组?

What is the easiest/shortest way to convert a Java 8 Stream into an array?

推荐答案

您可以使用的toArray 的重载版本,如下:

You can use the overloaded version of toArray, as the following:

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

IntFunction 1所述的目的; A []&GT;发电机是一个整数,该数组的大小,转换成一个新的数组。

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

举例code:

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

打印:

a
b
c

另一种选择是使用方法参照字符串数组构造函数,这个人是有点比较麻烦。使用方法很简单:

Another option is to use a method reference to the string array constructor, this one is a bit more tricky. Usage is easy:

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

它做什么,是发现,发生在一个整数(大小)作为参数的方法,并返回一个的String [] ,这正是(一个的重载)新的String [] 一样。

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.

这篇关于如何转换一个Java 8个流到数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-21 11:27