简体   繁体   English

Java 8中有哪种lambda表达式语法?

[英]What kind of lambda expression syntax is this in Java 8?

This is from one question about lambda expression. 这是关于lambda表达式的一个问题。 I'm baffled with the syntax in line check((h, l) -> h > l, 0); 我对行check((h, l) -> h > l, 0);的语法感到困惑check((h, l) -> h > l, 0); :

The check() function requires a Climb object and an int. check()函数需要一个Climb对象和一个int。 The line above does not provide any Climb object. 上面的行不提供任何Climb对象。 And what does h > l, 0 mean? h > l, 0是什么意思?

interface Climb {
  boolean isTooHigh(int height, int limit);
}

class Climber {
  public static void main(String[] args) {
    check((h, l) -> h > l, 0);
  }
  private static void check(Climb climb, int height) {
    if (climb.isTooHigh(height, 1)) 
      System.out.println("too high");
    else 
      System.out.println("ok");
  }
}

Your Climb interface respects the contract of a functional interface , that is, an interface with a single abstract method. Climb接口遵循功能接口的约定,即具有单个抽象方法的接口。

Hence, an instance of Climb can be implemented using a lambda expression, that is, an expression that takes two ints as parameters and returns a boolean in this case. 因此,可以使用lambda表达式实现Climb的实例,即,表达式将两个int作为参数并在此情况下返回布尔值。

(h, l) -> h > l is the lambda expression that implements it. (h, l) -> h > l是实现它的lambda表达式。 h and l are the parameters ( int ) and it will return whether h > l (so the result is indeed a boolean ). hl是参数( int ),它将返回是否h > l (所以结果确实是一个boolean )。 So for instance you could write: 所以你可以写一下:

Climb climb = (h, l) -> h > l;
System.out.println(climb.isTooHigh(0, 2)); //false because 0 > 2 is not true

Apparently, (h, l) -> h > l is a lambda expression where the result is of a boolean type and the 0 is the second argument of check , which is unrelated to the lambda expression itself; 显然, (h, l) -> h > l是一个lambda表达式,其结果是布尔类型, 0check的第二个参数,它与lambda表达式本身无关; the 0 does not belong to the lambda expression as such. 0不属于lambda表达式。

(h, l) -> h > l is the climb object. (h, l) -> h > l是爬升物体。 It is a lambda that returns true when the first argument (h) is greater than the second (l). 当第一个参数(h)大于第二个参数(l)时,它是一个返回true的lambda。 0 is the int, and the comma separates the arguments. 0是int,逗号分隔参数。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM