有没有一种方法可以使用简单的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));
}
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句