Convenient List Generation with java.util.stream.Stream
Let's assume you need a List
of class / record instances created with factory method.
The following snippet generates five UUIDs, instantiates a record
instance with the generated UUID and finally
converts the stream into a List<Developer>
:
import java.util.UUID;
import java.util.stream.Stream;
public class StreamGenerationTest {
@Test
public void listGenerationWithStream() {
record Developer(UUID id) {
}
var developerList = Stream.generate(UUID::randomUUID)
.limit(5)
.map(Developer::new)
.toList();
assertEquals(5, developerList.size());
System.out.println(developerList);
}
}
The output: [Developer[id=c914402a-93db-4234-a364-131bc5a8ebc2], Developer[id=5b3b16fd-d7cd-4f38-82a7-70923b9e0362], Developer[id=1910d38a-c74c-4535-9466-0e83ff591dbf], Developer[id=db8522c8-b291-439e-9bd7-03d9edc94716], Developer[id=1ec8ed08-dbd4-43f0-93b8-7d60dc1a8132]]
If you need a number as index, checkout: Convenient List Generation with java.util.stream.IntStream