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()};
An array is a fixed size element of the same type. The lambda expressions can also be used to initialize arrays in Java.
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.
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“.
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));
}
}
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);
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());
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With