Lambda Essay on Learning Java Core Technology Volume

Lambda expressions

  Form: parameter, arrow (->), expression

    The parameter type should be written, if it can be deduced, it can be omitted

    Only one parameter can omit the parentheses

    No arguments to write empty parentheses ()

    *If the branch returns a value, then all branches must return a value, otherwise it is illegal

   Functional interface: an interface with only one abstract method (can be marked with the @FunctionalInterface annotation)

    For example, javax.swing.Timer can be like this

      Timer t = new Timer(1000, event ->

      {

        …

      });

    The second parameter of this constructor requires an instance of ActionListener, ActionListener

    It is an interface with only one method, so lambda expressions can be used.

  method reference

    Object::instanceMethod

    Class::staticMethod

    Class::instanceMethod

    For example: event -> System.out.println(event) is equivalent to System.out :: println

      Math::pow is  equivalent to (x, y) -> Math.pow(x, y)

    In the third case, the first parameter will become the target of the method. For example: String::compareToIgnoreCase is equivalent to (x,y) -> x.compareToIgnoreCase(y)

    You can also use this and super parameters;

    Super :: instanceMethod

  Constructor reference:

    X -> new int[x] is equivalent to int[]::new

    Person x = New Person(…) is equivalent to Person::new

    When there are multiple constructors, the compiler deduces from the context

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325034134&siteId=291194637