“On the road to success, vitality is necessary, ambition is valuable, but more important is the boring almost ordinary perseverance and courage.” Hello, I am Mengyangchen, the future I grow up with you.

What is a Lambda expression? Lambda is an anonymous function, and we can think of a Lambda expression as a piece of code that can be passed (passing code like data).

Lambda allows functions to be passed as arguments to a method. Why Lambda expressions? You can write cleaner, more flexible code. As a more compact code style, Java’s expressiveness has improved.

Contrast:

import java.util.Comparator; import java.util.TreeSet; Public class LambdaTest {public void test1(){Comparator<Integer> com = new Comparator<Integer>() { @Override public int compare(Integer o1, Integer o2) { return Integer.compare(o1,o2); }}; TreeSet<Integer> ts = new TreeSet<>(com); Public void test2(){Comparator<Integer> com = (x,y) ->Integer.com (x,y); TreeSet<Integer> ts = new TreeSet<>(com); }}Copy the code

3. In Java8, the basic syntax for Lambda expressions, a new operator “->” has been introduced, called the arrow operator or Lambda operator. The arrow operator splits a Lambda expression into two parts.

Left: list of Lambda expressions (arguments in methods in the interface).

Right: the function that needs to be performed in the expression (the code implemented in the interface).

Syntax format:

() -> system.out.println (” Hello Lambda “);

Println (x) -> system.out.println (x);

public void test1(){
Consumer<String> con = (x) -> System.out.println(x);
con.accept("fda");
}
Copy the code

3. There is one argument that the parentheses can omit.

There are more than two arguments, and the Lambda body, there are multiple statements, have a return value. Compatator com = (x,y) ->{system.out.println (” functional interface “); Compatator com = (x,y) ->{system.out.println (” functional interface “); return Integer.compare(x,y); };

Public void test2(){Compatator<Integer> com = (x,y) ->{system.out.println (" functional interface "); return Integer.compare(x,y); }; }Copy the code

5. If there are more than two arguments and only one statement in the Lambda body, return and braces can be omitted.

com = (x,y) -> Integer.compare(x,y);
Copy the code

6. The data type of the argument list of a Lambda expression can be omitted because the JVM compiler can infer from context.

Lambda expressions can only refer to outer local variables that mark final (final can be omitted), which means that local variables defined outside of the domain cannot be modified inside the lambda, otherwise a compilation error will occur.

Lambda expressions require the support of functional interfaces

Functional interface: An interface that contains only one abstract method is called a functional interface.

You can check whether an interface is functional by using the @functionalInterface annotation.

Case 1: Implementing data operations:

@FunctionalInterface public interface Myfun { public Integer getValue(Integer num); // Abstract method}Copy the code

public class Test {
    public static void main(String[] args) {
      Integer num=  operation(100,x->x*x);//乘
      Integer num2=  operation(100,x->{
          int result = x+900;return result;});//乘
        System.out.println(num2);
    }

    /**
     * 对数据进行操作
     * @param num
     * @param mf
     * @return
     */
    public  static Integer operation(Integer num,Myfun mf){
        return  mf.getValue(num);
    }
}
Copy the code

Advanced exercise: 1. Call the collections.sort () method to compare two employees by custom sort(first by age, then by name), passing Lambda as an argument.

import java.util.*;

public class Test {
    public static void main(String[] args) {
        List<Employee> list  = Arrays.asList(
                new Employee("MengYangChen",18,2000),
                new Employee("Meng",21,1000),
                new Employee("MenaYang",21,20000)
        );

       /* Comparator<Employee> a  = new Comparator() {
            @Override
            public int compare(Object o1, Object o2) {
                return ;
            }
        }*/

       /* Comparator<Employee> e = (x,y)->{
            if(x.getAge()==y.getAge()){
                return x.getName().compareTo(y.getName());
            }
            return Integer.compare(x.getAge(),y.getAge());};*/

        Collections.sort(list,(x,y)->{
            if(x.getAge()==y.getAge()){
                return x.getName().compareTo(y.getName());
            }
            return Integer.compare(x.getAge(),y.getAge());});

        Iterator<Employee> it  = list.iterator();
        while (it.hasNext()){
            System.out.println(it.next().getName());
        }
     }
}
Copy the code

public class Employee { private String name; private int age; private double salary; public Employee(String name, int age, double salary) { this.name = name; this.age = age; this.salary = salary; } public String getName() { return name; } public void setName(String name) { this.name = name; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } public double getSalary() { return salary; } public void setSalary(double salary) { this.salary = salary; }}Copy the code

Public String getValue(String STR) public String getValue(String STR); TestLambda is a class in which methods that take interfaces as arguments convert a string to uppercase as the return value of the method. ③ Intercept the second and fourth index positions of a string.

@FunctionalInterface
public interface Myfunction {
   public String getValue(String str);
}
Copy the code

public class Test { public static void main(String[] args) { String upper = operate("abc",str->str.toUpperCase()); } public static String operate (String STR,Myfunction Myfun){return myfun.getValue (STR); }}Copy the code

3.① Declare a functional interface with two generic types. The generic type is

T is the parameter,R is the return value. TestLambda class = TestLambda class = TestLambda class = TestLambda class – ④ Calculate the product of two long parameters. –
,r>

package Chapters6.Lambda3; Public class Test {public static void main(String[] args) {operate(100,200,(x,y)->x+y); / / add operate (100200, (x, y) - > x * y); Public static void operate (double a,double b,Myfunction< double,double > myfun){public static void operate (double a,double b,Myfunction > myfun){ System.out.println(myfun.getValue(a,b)); }}Copy the code

package Chapters6.Lambda3;

@FunctionalInterface
public interface Myfunction <T,R>{
    public R getValue(T t1,T t2);
}
Copy the code

No matter what you’re going through, you have to pick yourself up from being down, keep your enthusiasm up, and keep smiling like you’ve never been hurt.