lamdba expressions can be simplified
The following introduces 6 ways to simplify lamdba, also known as method or constructor reference.
If a lambda expression represents just calling this method directly, it is better to call it by name instead of describing how to call it. Explicitly specifying the name of the method can make your code more readable.
1. The parameter category and return type must be consistent with the abstract method in the functional interface.
2. If the first parameter in the parameter list is the caller of the instance method and the second parameter is the parameter of the instance method, you can use ClassName: :method
Object::instance method - method reference
//用lambda表达式实现
Consumer consumer = x -> System.out.println(x);
consumer.accept("hello world");
//out实现了println方法
Consumer consumer1 =System.out::println;
consumer1.accept("hello word 1");
Class name:: static method - method reference
//用lambda表达式实现
BiFunction<Integer, Integer, Integer> biFun = (x,y) -> Integer.compare(x,y);
//类名::静态方法
BiFunction<Integer, Integer, Integer> biFun1 = Integer::compare;
int result1 = biFun.apply(100,200);
int result2 = biFun1.apply(100,200);
Class name::instance method - method reference
//用lambda表达式实现
BiFunction<String,String,Boolean> fun1 = (s1,s2)-> s1.equals(s2);
//类名::实例方法
BiFunction<String,String,Boolean> fun2 = String::equals;
fun1.apply("hello","hello");
fun2.apply("hello","hello");
Class name::new - constructor reference
//用lambda表达式实现
Supplier<String> sup = ()->new String();
//构造方法引用 类名::new
Supplier<String> sup1 = String::new;
Class name::new() - constructor reference
//用lambda表达式实现
Function<String,Integer> function = x->new Integer(x);
//类名::new
Function<String,Integer> function1 = Integer::new;
function1.apply("100");
String[]:::new --Array reference
//用lambda表达式实现
Function <Integer,String[]> array = x -> new String [x];
//类型[]::new
Function <Integer,String[]> array1 = String[]::new;
array1.apply(5);
All code execution results:
No error
1000
10
Process finished with exit code 0