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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-03 01:58:29  来源:igfitidea点击:

Lambda expression to initialize array

javalambdajava-8

提问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.setAllor Arrays.parallelSetAll:

如果您已经有一个预先分配的数组,则可以使用 lambda 表达式使用Arrays.setAllor填充它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);

回答by Maroun

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:

如果您想使用 Java 8 对其进行初始化,则实际上并不需要使用 lambda 表达式。您可以使用Stream以下方法实现:

Stream.of(new Person()).collect(Collectors.toList());