Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Initialize a list of strings with a function

I’m looking for a nice and simple way to create a list of strings given a function
something like:
List<String> list = new ArrayList(10, () -> createRandomString());

which will create a new list with 10 random values
by random values i mean that it doesn’t matter the value, more important that the lambda will return a string each invocation (10 invocations)

I can basically do a for loop but I’m looking for a more concise way

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

I’ve tried with Collections.fill() but it requires a list with values and we can fill the same value and not a different one for each invocation

does anyone knows a way to do that?

>Solution :

Stream.generate(() -> createRandomString())
            .limit(10)
            .collect(Collectors.toList());
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading