28

Is there a way to initialize an array or a collection by using a simple lambda expression?

Something like

// What about this?
Person[] persons = new Person[15];
persons = () -> {return new Person()};

Or

// I know, you need to say how many objects
ArrayList<Person> persons = () -> {return new Person()};

3 Answers 3

33

Sure - I don't know how useful it is, but it's certainly doable:

import java.util.*;
import java.util.function.*;
import java.util.stream.*;

public class Test
{
    public static void main(String[] args)
    {
        Supplier<Test> supplier = () -> new Test();
        List<Test> list = Stream
            .generate(supplier)
            .limit(10)
            .collect(Collectors.toList());
        System.out.println(list.size()); // 10
        // Prints false, showing it really is calling the supplier
        // once per iteration.
        System.out.println(list.get(0) == list.get(1));
    }
}
Sign up to request clarification or add additional context in comments.

2 Comments

Or directly .generate(() -> new Test()), just to use the lambda operator requested by OP... would rather use .generate(Test::new).
@Jean-FrançoisSavard: Yes, I was only separating out the declaration to show the types involved.
32

If you already have a pre-allocated array, you can use a lambda expression to populate it using Arrays.setAll or Arrays.parallelSetAll:

Arrays.setAll(persons, i -> new Person()); // i is the array index

To create a new array, you can use

Person[] persons = IntStream.range(0, 15)  // 15 is the size
    .mapToObj(i -> new Person())
    .toArray(Person[]::new);

Comments

1

If you want to initialize it using Java 8, you don't really need to use a lambda expression. You can achieve that using Stream:

Stream.of(new Person()).collect(Collectors.toList());

10 Comments

I think the OP wants to call the lambda expression multiple times to populate the list - see if my answer makes sense to you.
This will create a list containing a single Person instance, thus, it’s a complicated way to do the same as Collections.singletonList(new Person())
@Jean-FrançoisSavard: Collectors.toList() gives no guarantees about mutability or immutability, so that's not really a point in favor of this answer.
@Jean-François Savard: Collectors.toList() returns an unspecified list type so you can't assume mutability anyway. Theoretically, it could return exactly the same type for a single-element result. Only if immutability is required, singletonList is preferable.
@Ricola agreed. I was a kid back then.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.