当前位置:网站首页>Lambda expression | shallow solution
Lambda expression | shallow solution
2022-06-12 11:25:00 【Blue cotton】
Lambda expression
brief introduction
- Lambda Expressions support code blocks as method parameters , Allow more concise code to create an interface with only one abstract method ( It 's called a functional interface ) Example .
- Functional interface : An interface that contains only one abstract method .
- Lambda The expression is equivalent to an anonymous method .
- effect : Instead of the cumbersome syntax of anonymous inner classes .
- part : Parameter list ( Parameter types are allowed to be omitted , parentheses ); arrow -> ; Code block ( You can omit curly braces ,return)
- Lambda The expression will actually be treated as a Any type The object of .
- Lambda The essence of an expression is function .
( parameter list ) -> {
Method body ;
};
ordinary Lambda expression
- Implement... With anonymous inner classes :
// Functional interface : An interface that contains only one abstract method
interface Cal{
int add(int a, int b);
}
// This is our previous implementation , Anonymous inner class , Then the execution is called ;
public class Program {
public static void main(String[] args) {
// Anonymous inner class
Cal c1 = new Cal() {
// Rewrite implementation interface
@Override
public int add(int a, int b) {
return a+b;
}
};
// Calls to perform
int c = c1.add(1, 2);
System.out.println(c);
}
}
- use Lambda Expression rewriting :
// Functional interface : An interface that contains only one abstract method
interface Cal{
int add(int a, int b);
}
// use Lambda Expression rewriting :
public class Program {
public static void main(String[] args) {
//Lambda expression
Cal c1=(int a,int b) ->{
return a+b;
};
// Calls to perform
int c=c1.add(1,2);
System.out.println(c);
}
}
Lambda Expression syntax
- Make a case , Interface method parameters , No arguments , Single parameter , Two parameters , There is a return value , no return value , These six situations are listed below :
public class Test {
public static void main(String[] args) {
I1 i1 = () -> {
System.out.println(" No return value 、 No parameter ");
};
i1.test();// No return value 、 No parameter
I2 i2 = (int a, int b) -> {
System.out.println(" No return value , Multiple parameters .a=" + a + ", b=" + b);
};
i2.test(2, 3);// No return value , Multiple parameters .a=2, b=3
I3 i3 = () -> {
System.out.println(" There is a return value 、 No parameter ");
return 100;
};
System.out.println(i3.test());// There is a return value 、 No parameter 100
I4 i4 = (int a, int b) -> {
System.out.println(" There is a return value , Multiple parameters .a=" + a + ",b=" + b);
return a + b;
};
System.out.println(i6.test(2, 4));// There is a return value , Multiple parameters .a=2,b=4 6
}
}
interface I1 {
// No return value 、 No parameter
void test();
}
interface I2 {
// No return value , Multiple parameters
void test(int a, int b);
}
interface I3 {
// There is a return value 、 No parameter
int test();
}
interface I4 {
// There is a return value , Multiple parameters
int test(int a, int b);
}
Lambda Expression reduction Syntax
Parameter type It can be omitted .
If only One parameter ,() Brackets It can be omitted .
If the method body has only A sentence ,{} Curly braces It can be omitted .
If in the method body The only statement is return Return statement , When you omit the braces return You can omit it .
// Before omission
I6 i6=(int a, int b)->{
return a+b;
};
// Omit : Parameter type ,{} Curly braces ,return
I6 i6=(a,b)->a+b;
Method reference
- Sometimes more than one lambda If the expression implementation function is the same , We can encapsulate it as a generic method , To facilitate maintenance ;
- In this case, you can use method reference to implement :
Grammar is : object :: Method ( Need to be new An object )
if static Method : Class name :: Method ( There is no need to new An object , Direct class name )
public class Program2 {
public static void main(String[] args) {
// Method reference
// Common method Object name :: Method name ( Need to be new An object )
Program2 program2 = new Program2();
I5 i5 = program2::test;
System.out.println(i5.test(1));
// static Method Class name :: Method name ( There is no need to new An object , Direct class name )
I5 i52 = Program2::test2;
System.out.println(i52.test(1));
}
public int test(int a){
return a-2;
}
//static Method
public static int test2(int a){
return a-2;
}
}
interface I5{
// A single parameter has a return value
int test(int a);
}
Construction method reference
- If the implementation of a functional interface can happen through Call the constructor of a class to implement , Then you can use the constructor to reference ;
- grammar : Class name ::new
public class Program3 {
public static void main(String[] args) {
// The ordinary way
DogService dogService = ()->{
return new Dog();
};
dogService.getDog();
// Simplified method
DogService dogService2 = ()->new Dog();
dogService2.getDog();
// Construction method reference
DogService dogService3 = Dog::new;
dogService3.getDog();
// Construction method reference Ginseng
DogService2 dogService21 = Dog::new;
dogService21.getDog(" One, two, three ",8);
}
}
// In defining two interfaces :
interface DogService{
Dog getDog();
}
interface DogService2{
Dog getDog(String name,int age);
}
// So let's define one Dog Entity , Implementation of nonparametric and parametric construction methods
class Dog {
private String name;
private int age;
public Dog() {
System.out.println(" Nonparametric construction method ");
}
public Dog(String name, int age) {
System.out.println(" Parametric construction method ");
this.name = name;
this.age = age;
}
@Override
public String toString() {
return "Dog{" +
"name='" + name + '\'' +
", age=" + age +
'}';
}
}
@FunctionalInterface annotation
- This annotation is a functional interface annotation , So called functional interfaces , Of course, the first is an interface , Then there is only one abstract method in this interface .
- Interface has and only has one abstract method
- The annotation It's not necessary , If an interface conforms to " Functional interface " Definition , So it doesn't matter whether the annotation is added or not . Add this annotation to make the compiler better able to check . If you're not writing a functional interface , But with it @FunctionInterface, Then the compiler will report an error
The system has built-in functional interfaces
- Java8 Launch , In order to Lambda Important features , Together with , A series of functional interfaces are built into the system .
- Again jdk Of java.util.function It's a bag , There's a series of built-in functional interfaces : For example, common Consumer,Comparator,Predicate,Supplier etc. .
Lambda The relationship and difference between expressions and anonymous inner classes
- Lambda Expressions are a kind of anonymous inner classes simplify .
- The same thing :(1) Can be accessed directly “effectively final” Local variables of , And the member variables of the external class ;(2) Can directly call the default method inherited from the interface .
- difference :(1) Anonymous inner classes can be Any interface Create examples ,Lambda The expression can only be Functional interface Create examples ;(2) Anonymous inner classes can create instances for abstract classes and even different classes ;(3) Anonymous inner classes allow you to call the default methods defined in the interface .
Use Lambda Expression call Arrays Class method of
- Arrays Some methods of class need Comparator、XXXOperator、XXXFunction And other interfaces , It's all functional interfaces , So you can use Lambda Expression to call Arrays Class method of .
This paper is about Video Course Learning notes of , Add your own summary .
边栏推荐
- Grid layout
- ^33 variable promotion and function promotion interview questions
- MATLAB中stairs函数使用
- NLP data set download address for naturallanguageprocessing
- AcWing 41. 包含min函数的栈(单调栈)
- Immer source code reading
- Clickhouse column basic data type description
- Humans want to have money, power, beauty, eternal life and happiness... But turtles only want to be a turtle
- systemctl里万恶的203
- FormatConversionTool. exe
猜你喜欢

AcWing 131. The largest rectangle in the histogram (monotone stack classic application template)

K58. Chapter 1 installing kubernetes V1.23 based on kubeadm -- cluster deployment

网络的拓扑结构

Selenium uses proxy IP

Unity connect to Microsoft SQLSERVER database

The reason why scanf return value is ignored and its solution

Don't swallow rice with vinegar! Teach you 2 moves to make the fish bones "run out" safely

M-arch (fanwai 13) gd32l233 evaluation - some music
![[Blue Bridge Cup SCM 11th National race]](/img/da/3c8a9efd5b28f67816f239531a0339.png)
[Blue Bridge Cup SCM 11th National race]

Clj3-100alh30 residual current relay
随机推荐
AcWing 132. Group queue (queue simulation question)
2022-06-11:注意本文件中,graph不是邻接矩阵的含义,而是一个二部图。 在长度为N的邻接矩阵matrix中,所有的点有N个,matrix[i][j]
DS18B20 digital thermometer (I) electrical characteristics, parasitic power supply mode and remote wiring
[Blue Bridge Cup SCM 11th National race]
Clickhouse column basic data type description
redis 总结
The evil 203 in systemctl
Golang Foundation (6)
Windows10安装mysql-8.0.28-winx64
arm各种交叉编译工具的区别
SOT23(Small Outline Transistor)
AcWing 128. 编辑器(对顶栈 实现序列内部指定位置高效修改)
【藍橋杯單片機 國賽 第十一届】
k58.第一章 基于kubeadm安装kubernetes v1.23 -- 集群部署
记录一下使用JPA时遇到的坑
力扣(LeetCode)162. 寻找峰值(2022.06.11)
FPGA-按键实验
Unity 连接 Microsoft SQLSERVER 数据库
你需要社交媒体二维码的21个理由
Network topology