Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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()};
like image 882
David Marciel Avatar asked Apr 27 '16 09:04

David Marciel


People also ask

Can you use lambda expression array?

An array is a fixed size element of the same type. The lambda expressions can also be used to initialize arrays in Java.

How do you initialize an array?

The initializer for an array is a comma-separated list of constant expressions enclosed in braces ( { } ). The initializer is preceded by an equal sign ( = ). You do not need to initialize all elements in an array.

How do you initialize an array in Python?

To initialize an array in Python, use the numpy. empty() function. The numpy. empty() function creates an array of a specified size with a default value = “None“.


3 Answers

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));
    }
}
like image 190
Jon Skeet Avatar answered Oct 17 '22 02:10

Jon Skeet


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);
like image 24
Misha Avatar answered Oct 17 '22 04:10

Misha


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());
like image 4
Maroun Avatar answered Oct 17 '22 04:10

Maroun