David Marciel David Marciel - 6 months ago 14
Java Question

Lambda expression to initialize array

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()};


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


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