Lambda函数变成了BiConsumer

时间:2017-06-02 09:58:52

标签: java lambda

我想弄清楚它是如何工作的。
我将列出我认为正在发生的事情,希望有人可以告诉我,我错了。或者告诉我它是如何工作的。

public BiConsumer<List<T>, T> accumulator() {
    return List::add;
}
  1. 一个名为accumulator的方法,它不接受任何内容并返回BiConsumer方法。
  2. accumulatoradd的上下文中将引用返回到List方法BiConsumer
  3. add上的实际List方法实际上是Function<T, Boolean>,接收T并返回布尔值
  4. 这是我进入猜测领域的地方。

    1. 它正在add的实例上调用List方法,BiConsumerpublic BiConsumer<List<T>, T> accumulator() { return (list, item) -> list.add(i); } 的第一个参数。
    2. 我在内部知道它一定在做。

      add

      我了解它可以忽略Function<A, B>方法的返回类型,因此可以假装Consumer<A>BiConsumer

      但我只是不明白黑魔法会导致Consumer在第一个参数的实例上运行FunctionBiConsumer <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>

1 个答案:

答案 0 :(得分:1)

这不是黑魔法。它已明确指定Structure of the project

  

以下是对特定类型的任意对象的实例方法的引用示例:

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的东西时,它可以被转换为一个接受两个参数的函数,第一个是调用方法的实例。它只是可以,因为语言规范是这样说的。