Dav*_*iel 21 java lambda java-8
有没有办法使用简单的lambda表达式初始化数组或集合?
就像是
// What about this?
Person[] persons = new Person[15];
persons = () -> {return new Person()};
Run Code Online (Sandbox Code Playgroud)
要么
// I know, you need to say how many objects
ArrayList<Person> persons = () -> {return new Person()};
Run Code Online (Sandbox Code Playgroud)
Jon*_*eet 29
当然 - 我不知道它有多有用,但它肯定是可行的:
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));
}
}
Run Code Online (Sandbox Code Playgroud)
Mis*_*sha 21
如果您已经有预先分配的数组,则可以使用lambda表达式使用Arrays.setAll
或填充它Arrays.parallelSetAll
:
Arrays.setAll(persons, i -> new Person()); // i is the array index
Run Code Online (Sandbox Code Playgroud)
要创建新阵列,您可以使用
Person[] persons = IntStream.range(0, 15) // 15 is the size
.mapToObj(i -> new Person())
.toArray(Person[]::new);
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
11319 次 |
最近记录: |