问题
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