Understand Lambda expressions at a glance


Lambda expressions are a new feature of JDK8, which can replace most of the anonymous inner classes and write more elegant Java code, especially in the traversal of collections and other collection operations, which can greatly optimize the code structure.
New features of Lambda:

  1. Lambda 表达式,也可称为闭包,它是推动 Java 8 发布的最重要新特性。
  2. Lambda 允许把函数作为一个方法的参数(函数作为参数传递进方法中)。
  3. 使用 Lambda 表达式可以使代码变的更加简洁紧凑。

Important features of Lambda:

  • Optional type declaration : there is no need to declare the parameter type, the compiler can uniformly identify the parameter value.
  • Optional parameter parentheses : one parameter does not need to define parentheses, but multiple parameters need to define parentheses.
  • Optional curly braces : If the body contains a statement, curly braces are not required.
  • Optional return keyword : If the subject has only one expression return value, the compiler will automatically return the value. The braces need to specify that the expression returns a value.

Lambda basic syntax

/**多个参数有返回值*/
@FunctionalInterface
public interface ReturnMultiParam {
    
    
    int method(int a, int b);
}

@FunctionalInterface
Repair decorative function interface , requiring an abstract interface is only one method . This annotation often appears with lambda expressions.

The syntax form is () -> {}, where () is used to describe the parameter list, {} is used to describe the method body, -> is the lambda operator, pronounced (goes to).

Lambda syntax simplification

The corresponding method call is:

   //多个参数有返回值
        ReturnMultiParam returnMultiParam = (int a, int b) -> {
    
    
            System.out.println("ReturnMultiParam param:" + "{" + a + "," + b +"}");
            return 1;
        };
        int res3 = returnMultiParam.method(6, 8);

The method can also be more concise:

1. 只有一个参数可以省略括号  (int a) >> a  ,且省略参数类型
2. 如果方法体中只有一个语句,则可以省略括号   
   ReturnMultiParam returnMultiParam =  a ->System.out.println("ReturnMultiParam param:" + a);
3. 如上是省略大括号的 有return值的 表达式
   ReturnMultiParam returnMultiParam =  a -> 1 + a;
4. //lambda4 引用了已经实现的 addTwo 方法
   Exe1 exe = new Exe1();
   ReturnOneParam lambda4 = exe::addTwo; // 调用非静态方法
   ReturnOneParam lambda5 = Exe1 ::addTwo2; // 调用静态方法

Construction method reference

   interface ItemCreatorParamContruct {
    
    
        Item getItem(int id, String name, double price);
    }

Lambda use of the construction method:

        ItemCreatorParamContruct creator3 = Item::new;
        Item item3 = creator3.getItem(112, "鼠标", 135.99);

Equivalent to regular expressions

  ItemCreatorParamContruct creator4 = new ItemCreatorParamContruct() {
    
    
            @Override
            public Item getItem(int id, String name, double price) {
    
    
                return new Item(id, name, price);
            }
        };
        creator4.getItem(112, "鼠标", 135.99);

Use of collections

  1. Traversal of collection
      @RequiresApi(api = Build.VERSION_CODES.N)
        ArrayList<Integer> list = new ArrayList<>();
        //lambda表达式 方法引用
        list.forEach(System.out::println);
        list.forEach(element -> {
    
    
            if (element % 2 == 0) {
    
    
                System.out.println(element);
            }
        });
  1. Delete elements in the collection
    ArrayList<Item> items = new ArrayList<>();
    items.removeIf(ele -> ele.getId() == 7);
  1. Sorting of elements in the collection
     ArrayList<Item> list = new ArrayList<>();
     list.sort((o1, o2) -> o1.getId() - o2.getId());

Recommended link:

Guess you like

Origin blog.csdn.net/luo_boke/article/details/105593241