gpt4 book ai didi

java - Lambda 函数变成了 BiConsumer

转载 作者:行者123 更新时间:2023-11-30 10:28:56 26 4
gpt4 key购买 nike

我正在尝试弄清楚它是如何工作的。
我将列出我认为正在发生的事情,希望有人能告诉我我在某些地方错了。或者告诉我这是如何/为什么有效的。

public BiConsumer<List<T>, T> accumulator() {
return List::add;
}
  1. 一个名为 accumulator 的方法,它不接受任何内容并返回一个 BiConsumer 方法。
  2. accumulator返回对 add引用 List 上下文中的方法作为 BiConsumer
  3. 实际add List 上的方法实际上是一个 Function<T, Boolean> , 收录 T并返回一个 boolean 值

这是我进入猜测领域的地方。

  1. 它正在调用 add方法,在 List 的实例上这是 BiConsumer 的第一个参数.

我在内部知道它一定在做。

public BiConsumer<List<T>, T> accumulator() {
return (list, item) -> list.add(i);
}

我知道它可以忽略 add 的返回类型方法,所以它可以假装Function<A, B>Consumer<A>

但我只是不明白将 BiConsumer 变成的黑魔法运行 ConsumerFunctionBiConsumer 的第一个参数的实例上.

最佳答案

这不是黑魔法。详细说明 here .

The following is an example of a reference to an instance method of an arbitrary object of a particular type:

String[] stringArray = { "Barbara", "James", "Mary", "John",
"Patricia", "Robert", "Michael", "Linda" };
Arrays.sort(stringArray, String::compareToIgnoreCase);

The equivalent lambda expression for the method reference String::compareToIgnoreCase would have the formal parameter list (String a, String b), where a and b are arbitrary names used to better describe this example. The method reference would invoke the method a.compareToIgnoreCase(b).

当您有类似SomeType::instanceMethod 的东西时,它可以转换为接受两个参数的函数,第一个是调用方法的实例。它只是可以,因为语言规范是这么说的。

关于java - Lambda 函数变成了 BiConsumer,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44326097/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com