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