当前位置:网站首页>Several simplified forms of lambda expression

Several simplified forms of lambda expression

2022-07-05 00:28:00 ZZYSY~

For a functional interface ( There is only one method interface ), We can use lambda Expression to realize its , Here's how to use lambda Several simplified forms of expression

  1. Conventional form ( There are parameter types , There are brackets , There are curly braces. )
public class lamda {
    

    public static void main(String[] args) {
    
        Hello like = (int i)->{
    
            System.out.println("hello" + i);
        };
        like.hello(5);
    }
}
interface Hello {
    
     void hello(int i);
}
  1. Simplified parameter type

For methods that have no parameters or one parameter :

Can be simplified

public class lamda {
    

    public static void main(String[] args) {
    
        Hello like = (i)->{
    
            System.out.println("hello" + i);
        };
        like.hello(5);
    }
}
interface Hello {
    
     void hello(int i);
}

For methods with multiple parameters :

To simplify , All simplified

public class lamda {
    

    public static void main(String[] args) {
    

        Hello like = (i,j)->{
    
            System.out.println("hello" + i + j);
        };

        like.hello(5,"world");
    }
}
interface Hello {
    
     void hello(int i,String j);
}
  1. Simplified brackets

For methods that have no parameters or one parameter :

Can be simplified

public class lamda {
    

    public static void main(String[] args) {
    

        Hello like = i->{
    
            System.out.println("hello" + i);
        };

        like.hello(5,);
    }
}
interface Hello {
    
     void hello(int i);
}

For methods with multiple parameters :

Irreducible parentheses
 Insert picture description here

  1. Simplify curly braces

For methods with only one line of code :

Can be simplified

public class lamda {
    
    public static void main(String[] args) {
    
        Hello like = (i,j)->System.out.println("hello" + i + j);
        like.hello(5,"world");
    }
}
interface Hello {
    
     void hello(int i,String j);
}

For methods with multiple lines of code :

Do not simplify curly braces
 Insert picture description here
summary :

  • The premise is that the interface is functional ( There is only one method interface )
  • All the above simplified forms can be used together , That is, the parameter type can be simplified , You can also simplify parentheses
  • lambda An expression can only be simplified to one line if it has only one line of code , If there are many lines , Then wrap it in code blocks .
  • Multiple parameters can also be swept parameter types , If you want to get rid of everything , It has to be bracketed
原网站

版权声明
本文为[ZZYSY~]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/02/202202141120045611.html