Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
198 views
in Technique[技术] by (71.8m points)

java - 如何将Java 8 Stream转换为数组?(How to convert a Java 8 Stream to an Array?)

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

  ask by translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

The easiest method is to use the toArray(IntFunction<A[]> generator) method with an array constructor reference.

(最简单的方法是将toArray(IntFunction<A[]> generator)方法与数组构造函数引用一起使用。)

This is suggested in the API documentation for the method .

(在API文档中建议该方法 。)

String[] stringArray = stringStream.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.

(它的作用是找到一个以整数(大小)作为参数的方法,并返回String[] ,而这正是new String[] (的重载之一)所做的事情。)

You could also write your own IntFunction :

(您也可以编写自己的IntFunction :)

Stream<String> stringStream = ...;
String[] stringArray = stringStream.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.

(IntFunction<A[]> generator是将整数(数组的大小)转换为新数组。)

Example code:

(示例代码:)

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

Prints:

(打印:)

a
b
c

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

56.9k users

...