我想弄清楚它是如何工作的。
我将列出我认为正在发生的事情,希望有人可以告诉我,我错了。或者告诉我它是如何工作的。
public BiConsumer<List<T>, T> accumulator() {
return List::add;
}
accumulator
在add
的上下文中将引用返回到List
方法BiConsumer
add
上的实际List
方法实际上是Function<T, Boolean>
,接收T
并返回布尔值这是我进入猜测领域的地方。
add
的实例上调用List
方法,BiConsumer
是public BiConsumer<List<T>, T> accumulator() {
return (list, item) -> list.add(i);
}
的第一个参数。 我在内部知道它一定在做。
add
我了解它可以忽略Function<A, B>
方法的返回类型,因此可以假装Consumer<A>
为BiConsumer
但我只是不明白黑魔法会导致Consumer
在第一个参数的实例上运行Function
或BiConsumer
<html>
<head>
<style>
.cols_ex {
-webkit-columns: 4 10px;
-moz-columns: 4 10px;
columns: 4 10px;
-webkit-column-gap: 2em;
-moz-column-gap: 2em;
column-gap: 2em;
-webkit-column-rule: 2px dashed gray;
-moz-column-rule: 2px dashed gray;
column-rule: 2px dashed gray;
}
</style>
</head>
<body>
<div class="cols_ex">
<p>Just at this moment her head struck against the roof of the hall: in fact she was now rather more than nine feet high, and she at once took up the little golden key and hurried off to the garden door.</p>
<p>Poor Alice! It was as much as she could do, lying down on one side, to look through into the garden with one eye; but to get through was more hopeless than ever: she sat down and began to cry again.</p>
<p>"You ought to be ashamed of yourself," said Alice,"a great girl like you" (she might well say this), "to go on crying in this way! Stop this moment, I tell you!"</p>
<p>But she went on all the same, shedding gallons of tears,until there was a large pool all round her, about four inches deep, and reaching half down the hall.</p>
</div>
</body>
</html>
。
答案 0 :(得分:1)
以下是对特定类型的任意对象的实例方法的引用示例:
String[] stringArray = { "Barbara", "James", "Mary", "John", "Patricia", "Robert", "Michael", "Linda" }; Arrays.sort(stringArray, String::compareToIgnoreCase);
方法引用
String::compareToIgnoreCase
的等效lambda表达式将具有形式参数列表(String a, String b)
,其中a和b是用于更好地描述此示例的任意名称。方法引用将调用方法a.compareToIgnoreCase(b)
。
当你有类似SomeType::instanceMethod
的东西时,它可以被转换为一个接受两个参数的函数,第一个是调用方法的实例。它只是可以,因为语言规范是这样说的。