有没有一种方式可以使用简单的lambda表达式来初始化数组或集合?
就像这样:
// What about this?
Person[] persons = new Person[15];
persons = () -> {return new Person()};
或者
// I know, you need to say how many objects
ArrayList<Person> persons = () -> {return new Person()};
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));
}
}
Arrays.setAll
或Arrays.parallelSetAll
:Arrays.setAll(persons, i -> new Person()); // i is the array index
Person[] persons = IntStream.range(0, 15) // 15 is the size
.mapToObj(i -> new Person())
.toArray(Person[]::new);
如果您想使用Java 8进行初始化,您不需要使用lambda表达式。您可以使用Stream
来实现:
Stream.of(new Person()).collect(Collectors.toList());
Collectors.toList()
并不保证可变性或不可变性,所以这并不能成为支持此答案的论据。 - user2357112Collectors.toList()
返回一个未指定的列表类型,因此您无法假设可变性。理论上,对于单个元素结果,它可以返回完全相同的类型。仅在需要不可变性时,singletonList
更可取。 - Holger