27

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));
    }
}
2
  • 3
    Or directly .generate(() -> new Test()), just to use the lambda operator requested by OP... would rather use .generate(Test::new). Apr 27, 2016 at 13:46
  • 6
    @Jean-FrançoisSavard: Yes, I was only separating out the declaration to show the types involved.
    – Jon Skeet
    Apr 27, 2016 at 14:05
26

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

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());
8
  • 3
    I think the OP wants to call the lambda expression multiple times to populate the list - see if my answer makes sense to you.
    – Jon Skeet
    Apr 27, 2016 at 9:23
  • @JonSkeet Totally makes sense.
    – Maroun
    Apr 27, 2016 at 9:27
  • 3
    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())
    – Holger
    Apr 27, 2016 at 10:09
  • @Holger singletonList return an immutable list. Apr 27, 2016 at 13:51
  • 1
    @Jean-FrançoisSavard: Collectors.toList() gives no guarantees about mutability or immutability, so that's not really a point in favor of this answer. Apr 27, 2016 at 16:54

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.