如何在Java 8中将流的结果收集到自定义对象的数组中 [英] How to collect result of a stream into an array of custom object in Java 8

查看:117
本文介绍了如何在Java 8中将流的结果收集到自定义对象的数组中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个List<TestBuilder> testBuilders; Test具有Test类型的功能构建

I have an List<TestBuilder> testBuilders; Test has a function build of type Test

我做了testBuilders.stream().map(Test::build()).collect()

我想在array of Test i.e Test[]

我不确定collect function

推荐答案

使用终端操作 IntFunction<A[]> 分配返回数组的类型:

Use the terminal operation Stream::toArray which packs the sequence of items into an array. However, you have to define a provided generator IntFunction<A[]> to allocate the type of returned array:

Test[] array = testBuilders.stream().map(Test::build()).toArray(size -> new Test[size]);

lambda表达式size -> new Test[size]应该替换为方法引用:

The lambda expression size -> new Test[size] should be replaced with a method reference:

Test[] array = testBuilders.stream().map(Test::build()).toArray(Test[]::new);

这篇关于如何在Java 8中将流的结果收集到自定义对象的数组中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆