Search code examples
javalambdajava-8

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

Or

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

Solution

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