关于两参数方法参考的困惑

Lv.*_*ian 5 java lambda java-8 method-reference

我对该方法参考语法有些困惑。

counter()预计一BiFunction不过HighTemp::lessThanTemp是,尽管有效的参数HighTemp.lessThanTemp()只带一个参数。

该行中到底发生了if (f.func(vals[i], v))什么?

MCVE:

import java.util.function.BiFunction;

class Demo {
  static class HighTemp {
    private int hTemp;

    HighTemp(int ht) { hTemp = ht; }

    boolean lessThanTemp(HighTemp ht2) {
      return hTemp < ht2.hTemp;
    }
  }

  static <T> int counter(T[] vals, BiFunction<T,T,Boolean> f, T v) {
    int count = 0;

    for (int i=0; i < vals.length; i++) {
      if (f.apply(vals[i], v)) { // THIS LINE
        count++;
      }
    }

    return count;
  }

  public static void main(String args[]) {    
    HighTemp[] weekDayHighs2 = { new HighTemp(32), new HighTemp(12),
                                 new HighTemp(24), new HighTemp(19),
                                 new HighTemp(18), new HighTemp(12),
                                 new HighTemp(-1), new HighTemp(13) };

    int count = counter(weekDayHighs2, HighTemp::lessThanTemp, new HighTemp(19));
    System.out.println(count + " days had a high of less than 19");
  }
}
Run Code Online (Sandbox Code Playgroud)

dim*_*414 4

看一下相关的文档,里面有这样的注释:

方法引用的等效 lambda 表达式String::compareToIgnoreCase将具有形式参数 list (String a, String b),其中ab是用于更好地描述此示例的任意名称。方法引用将调用该方法a.compareToIgnoreCase(b)

换句话说,HighTemp::lessThanTemp等价于 lambda 表达式:

(a, b) -> a.lessThanTemp(b)
Run Code Online (Sandbox Code Playgroud)