lambda expression notes

A few days ago a friend shared an article which talked about lambda expressions, just recently read some of the content, it is doing the right notes ...

lambda expressions serve the function interface, if a subject in need of interface function, a lambda expression can be replaced by

What is the function interface?

1. The main point is that only contains an abstract interface method (Method Object class not ah)
2 must be annotated with @FunctionalInterface function interface, but this does not mean there is no comment on indicates otherwise, as long as a interfaces, and only an abstract method, it is the function interface, the compiler can annotate with good secondary, we in the custom function interface, will be more intuitive and helps readability

Few simple examples

Arrays.sort method requires a realization of the instance Comparator interface, under normal circumstances, we need to create an instance, then implement Comparator interface, and then pass the instance Arrays.sort method, it is quite cumbersome, but the use of lambda expressions It can be very simplified

If the compiler can deduce the parameter type, the parameter type in the parentheses may be omitted

        String[] array = new String[3];
        array[0] = "ccc";
        array[1] = "bb";
        array[2] = "a";
        System.out.println(array[0]);// 输出ccc
        Arrays.sort(array, (first, second) -> first.length() - second.length());
        System.out.println(array[0]);// 输出a

For more complex logic code, logic processing section may be used to wrap {}

        Timer t = new Timer(1000, event -> {
            System.out.println("action");
            System.out.println("listener");
        });
        t.start();

Expression also can be used as a parameter passed

        String[] array = new String[3];
        array[0] = "ccc";
        array[1] = "bb";
        array[2] = "a";
        System.out.println(array[0]);
        Comparator<String> comp = (first, second) -> first.length() - second.length();
        Arrays.sort(array, comp);
        System.out.println(array[0]);

If you do not enter parameters when parentheses can not be omitted

        Thread thread = new Thread(() -> {
            for (int i = 0; i < 100; i++) {
                System.out.println(i);
            }
        });
        thread.start();

The main job now is to use the Scala language, grammar, etc. Scala in contrast to Java in terms of more functions, traverse, sorting, filtering, and other operations even in terms of only one line of code to complete

But lambda as a big update Java8, we still need to learn about the new features

Guess you like

Origin www.cnblogs.com/pengx/p/11485912.html
Recommended