Getting started with Lambda expressions, this article is enough!

Author: Source to Sea: www.cnblogs.com/haixiang/p/11029639.html

Introduction to Lambda

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.

JDK also provides a large number of built-in functional interfaces for us to use, making the use of Lambda expressions more convenient and efficient.

Requirements for the interface

Although some interfaces can be easily implemented using Lambda expressions, not all interfaces can be implemented using Lambda expressions. Lambda stipulates that there can only be one method in the interface that needs to be implemented, not that there can be only one method in the interface

There is another new feature in jdk 8: default , the method modified by default will have a default implementation, which is not a method that must be implemented, so it does not affect the use of Lambda expressions.

@FunctionalInterface

Modification of a functional interface requires only one abstract method in the interface. This annotation often appears together with lambda expressions.

Lambda basic syntax

We give six interfaces here, and all operations in the following will use these six interfaces to explain.

/**多参数无返回*/
@FunctionalInterface
public interface NoReturnMultiParam {
    void method(int a, int b);
}

/**无参无返回值*/
@FunctionalInterface
public interface NoReturnNoParam {
    void method();
}

/**一个参数无返回*/
@FunctionalInterface
public interface NoReturnOneParam {
    void method(int a);
}

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

/*** 无参有返回*/
@FunctionalInterface
public interface ReturnNoParam {
    int method();
}

/**一个参数有返回值*/
@FunctionalInterface
public interface ReturnOneParam {
    int method(int a);
}

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

import lambda.interfaces.*;

public class Test1 {
    public static void main(String[] args) {

        //无参无返回
        NoReturnNoParam noReturnNoParam = () -> {
            System.out.println("NoReturnNoParam");
        };
        noReturnNoParam.method();

        //一个参数无返回
        NoReturnOneParam noReturnOneParam = (int a) -> {
            System.out.println("NoReturnOneParam param:" + a);
        };
        noReturnOneParam.method(6);

        //多个参数无返回
        NoReturnMultiParam noReturnMultiParam = (int a, int b) -> {
            System.out.println("NoReturnMultiParam param:" + "{" + a +"," + + b +"}");
        };
        noReturnMultiParam.method(6, 8);

        //无参有返回值
        ReturnNoParam returnNoParam = () -> {
            System.out.print("ReturnNoParam");
            return 1;
        };

        int res = returnNoParam.method();
        System.out.println("return:" + res);

        //一个参数有返回值
        ReturnOneParam returnOneParam = (int a) -> {
            System.out.println("ReturnOneParam param:" + a);
            return 1;
        };

        int res2 = returnOneParam.method(6);
        System.out.println("return:" + res2);

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

        int res3 = returnMultiParam.method(6, 8);
        System.out.println("return:" + res3);
    }
}

Lambda syntax simplification

We can further simplify the code by observing the following code and write more elegant code.

import lambda.interfaces.*;

public class Test2 {
    public static void main(String[] args) {

        //1.简化参数类型,可以不写参数类型,但是必须所有参数都不写
        NoReturnMultiParam lamdba1 = (a, b) -> {
            System.out.println("简化参数类型");
        };
        lamdba1.method(1, 2);

        //2.简化参数小括号,如果只有一个参数则可以省略参数小括号
        NoReturnOneParam lambda2 = a -> {
            System.out.println("简化参数小括号");
        };
        lambda2.method(1);

        //3.简化方法体大括号,如果方法条只有一条语句,则可以胜率方法体大括号
        NoReturnNoParam lambda3 = () -> System.out.println("简化方法体大括号");
        lambda3.method();

        //4.如果方法体只有一条语句,并且是 return 语句,则可以省略方法体大括号
        ReturnOneParam lambda4 = a -> a+3;
        System.out.println(lambda4.method(5));

        ReturnMultiParam lambda5 = (a, b) -> a+b;
        System.out.println(lambda5.method(1, 1));
    }
}

Common examples of lambda expressions

Lambda expression reference method

Sometimes we don't have to rewrite the method of an anonymous inner class by ourselves, we can use the interface of lambda expression to quickly point to an already implemented method. Follow the public number Java technology stack reply to get the Java8 series of tutorials I wrote.

grammar

Method owner:: method name Static method owner is the class name, ordinary method owner is the object

public class Exe1 {
    public static void main(String[] args) {
        ReturnOneParam lambda1 = a -> doubleNum(a);
        System.out.println(lambda1.method(3));

        //lambda2 引用了已经实现的 doubleNum 方法
        ReturnOneParam lambda2 = Exe1::doubleNum;
        System.out.println(lambda2.method(3));

        Exe1 exe = new Exe1();

        //lambda4 引用了已经实现的 addTwo 方法
        ReturnOneParam lambda4 = exe::addTwo;
        System.out.println(lambda4.method(2));
    }

    /**
     * 要求
     * 1.参数数量和类型要与接口中定义的一致
     * 2.返回值类型要与接口中定义的一致
     */
    public static int doubleNum(int a) {
        return a * 2;
    }

    public int addTwo(int a) {
        return a + 2;
    }
}

Construction method reference

Generally we need to declare an interface, which acts as a generator of an object, instantiates the object by way of class name::new, and then calls a method to return the object.

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

public class Exe2 {
    public static void main(String[] args) {
        ItemCreatorBlankConstruct creator = () -> new Item();
        Item item = creator.getItem();

        ItemCreatorBlankConstruct creator2 = Item::new;
        Item item2 = creator2.getItem();

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

lambda expression creates thread

We used to create Thread objects and then rewrite the run() method through anonymous inner classes. When we mention anonymous inner classes, we should think that we can use lambda expressions to simplify the process of thread creation.

ArrayList<Integer> list = new ArrayList<>();

Collections.addAll(list, 1,2,3,4,5);

//lambda表达式 方法引用
list.forEach(System.out::println);

list.forEach(element -> {
  if (element % 2 == 0) {
    System.out.println(element);
  }
});

Delete an element in the collection

We use public boolean removeIf(Predicate<? super E> filter)methods to delete an element in the collection. Predicate is also a functional interface provided by jdk, which can simplify program writing.

ArrayList<Item> items = new ArrayList<>();
items.add(new Item(11, "小牙刷", 12.05 ));
items.add(new Item(5, "日本马桶盖", 999.05 ));
items.add(new Item(7, "格力空调", 888.88 ));
items.add(new Item(17, "肥皂", 2.00 ));
items.add(new Item(9, "冰箱", 4200.00 ));

items.removeIf(ele -> ele.getId() == 7);

//通过 foreach 遍历,查看是否已经删除
items.forEach(System.out::println);

Sorting of elements in the collection

In the past, if we wanted to sort the elements in the collection, we had to call the sort method and pass in the anonymous internal class of the comparator to override the compare method. Now we can use lambda expressions to simplify the code.

ArrayList<Item> list = new ArrayList<>();
list.add(new Item(13, "背心", 7.80));
list.add(new Item(11, "半袖", 37.80));
list.add(new Item(14, "风衣", 139.80));
list.add(new Item(12, "秋裤", 55.33));

/*
list.sort(new Comparator<Item>() {
    @Override
    public int compare(Item o1, Item o2) {
        return o1.getId()  - o2.getId();
    }
});
*/

list.sort((o1, o2) -> o1.getId() - o2.getId());

System.out.println(list);

Closure problems in lambda expressions

This problem also exists in anonymous inner classes. If we put the comment in the meeting and report an error, tell me that the num value is final and cannot be changed. Although we did not mark the num type as final, the virtual machine helped us add final modified keywords during compilation.

import java.util.function.Consumer;
public class Main {
    public static void main(String[] args) {

        int num = 10;

        Consumer<String> consumer = ele -> {
            System.out.println(num);
        };

        //num = num + 2;
        consumer.accept("hello");
    }
}

Recommended recent hot articles:

1. 6 ways to get IntelliJ IDEA activation code for free!

2. I used Java 8 to write a piece of logic, and my colleagues couldn't understand it directly. You can try it. .

3. Sling Tomcat, Undertow performance is very explosive! !

4. The Chinese open sourced a super easy-to-use Redis client, which is so fragrant! !

5. The latest release of "Java Development Manual (Songshan Edition)", download it quickly!

Feel good, don't forget to like + forward!

Feel good, don’t forget to like + forward!

Finally, pay attention to the WeChat official account of the stack leader: Java technology stack, reply: Welfare, you can get a free copy of the latest Java interview questions I have compiled for 2020. It is really complete (including answers), without any routine.

Guess you like

Origin blog.csdn.net/youanyyou/article/details/108515061