【问题标题】:What is the equivalent for Bicycle[]::newBicycle[]::new 的等价物是什么
【发布时间】:2019-10-08 22:59:27
【问题描述】:

在下面的代码中有这样的语句:.toArray(Bicycle[]::new)。与此语句等效的 Lambda 是什么?

我检查了 toArray 是否接收到 IntFunction 的实现。如果我理解正确,IntFunction 是一个接口函数,它有一个可以接收 int 并返回 Bicycle [] 的应用方法。我不知道它接收到的这个 int 是什么来尝试安装 Lambda 等效项。

package br.com.testes;

import java.util.Arrays;
import java.util.List;

public class TesteMethodReference {

    public static void main(String[] args) {

        List<String> bikeBrands = Arrays.asList("Giant", "Scott", "Trek", "GT");

        Bicycle[] bicycles = bikeBrands.stream()
          .map(Bicycle::new) //the same .map((brand) -> new Bicycle(brand))
          .toArray(Bicycle[]::new); //WHAT IS THE LAMBDA EQUIVALENT?

        System.out.println(Arrays.deepToString(bicycles));

    }

}

class Bicycle {

    private String brand;

    public Bicycle(String brand) {
        this.brand = brand;
    }

    public String getBrand() {
        return brand;
    }

    public void setBrand(String brand) {
        this.brand = brand;
    }

    @Override
    public String toString() {
        return "Bicycle [brand=" + brand + "]";
    }
}

谁能帮我理解一下?

谢谢

【问题讨论】:

  • (size) -&gt; new Bicycle[size] - 这是一个数组构造函数

标签: java lambda java-8 method-reference


【解决方案1】:

&lt;A&gt; A[] toArray​(IntFunction&lt;A[]&gt; generator) 文档中的 API 说明

生成器函数取一个整数,即大小 所需的数组,生成所需大小的数组

这也相当于 Bergi 在 cmets 中指出的:

.toArray(size -> new Bicycle[size])

【讨论】:

    猜你喜欢
    • 2011-05-13
    • 1970-01-01
    • 2014-05-08
    • 2014-06-12
    • 1970-01-01
    • 2022-11-28
    • 1970-01-01
    • 1970-01-01
    • 2018-07-10
    相关资源
    最近更新 更多