5

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

Samuel Philipp
  • 10,631
  • 12
  • 36
  • 56
  • Not really related but: are you sure you want to have list of test builders? Should one builder produce only one test, or one builder should produce N tests? If one builder should generate N tests you could use code like `Stream.generate(someSingleTestBuilder::build).limit(N).toArray(Test[]::new);` – Pshemo Apr 30 '19 at 18:59
  • 1
    Possibly related: [Java 8 fill array with supplier](https://stackoverflow.com/q/25077203) – Pshemo Apr 30 '19 at 19:02

2 Answers2

6

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);
Nikolas Charalambidis
  • 40,893
  • 16
  • 117
  • 183
5

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.

GhostCat
  • 137,827
  • 25
  • 176
  • 248