How to collect result of a stream into an array of custom object in Java 8 [duplicate]

泄露秘密 提交于 2020-01-06 08:38:10

问题


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

I did testBuilders.stream().map(Test::build()).collect()

I want to collect above in array of Test i.e Test[]

I am not sure what would go in collect function


回答1:


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]);

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

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



回答2:


You can use

whatever.stream().toArray(WhatEverClass[]::new);

to create an array for objects of type WhatEverClass based on "whatever" stream of objects of that type. Thus: no need to collect() anything.



来源:https://stackoverflow.com/questions/55927132/how-to-collect-result-of-a-stream-into-an-array-of-custom-object-in-java-8

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!