java 用于初始化数组的 Lambda 表达式
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/36885371/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Lambda expression to initialize array
提问by David Marciel
Is there a way to initialize an array or a collection by using a simple lambda expression?
有没有办法使用简单的 lambda 表达式来初始化数组或集合?
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()};
回答by Jon Skeet
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));
}
}
回答by Misha
If you already have a pre-allocated array, you can use a lambda expression to populate it using Arrays.setAll
or Arrays.parallelSetAll
:
如果您已经有一个预先分配的数组,则可以使用 lambda 表达式使用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);