A new feature of JDK -- Magic operation of lambda expression

Small herdsman 2020-11-07 20:19:10
new feature jdk magic operation


One 、Lambda The introduction of expressions

  • Lambda Expression is Java8 One of the most important new features in . Use Lambda expression
    Can replace the interface implementation with only one abstract function , Farewell to anonymous inner classes , Look at the code
    It's easier to understand .Lambda The expression also enhances the set 、 Iteration of the framework 、
    Traverse 、 The operation of filtering data .

  • lambda An expression can replace an interface implementation with only one abstract function , Farewell to anonymous inner classes , The code looks simpler and easier to understand

  • lambda The expression also enhances the set 、 Iteration of the framework 、 Traverse 、 The operation of filtering data

  • lambda Can greatly reduce code redundancy , At the same time, the readability of the code is better than that of lengthy inner classes , An anonymous class

For example, we used to use anonymous inner classes to implement code :

 Runnable runnable = new Runnable() {
@Override
public void run() {
System.out.println("running1 .....");
}
};
runnable.run();

Use lambda Expressions implement simpler code :

 Runnable runnable3 = ()-> System.out.println("running2....");
runnable3.run();

lambda Expression syntax :

LambdaParameters -> LambdaBody

 Insert picture description here
args -> expr perhaps (object ... args)-> { Functional interface abstract method implementation logic }

​ 1、() Number of parameters , According to the number of abstract parameters in the functional interface , When there is only one parameter ,() It can be omitted

​ 2、 When expr When the logic is very simple ,{} and return It can be omitted

Case description :

 public static void main(String[] args) throws Exception {
Callable<String> c1 = new Callable() {
@Override
public String call() throws Exception {
return "muxiaonong";
}
};
System.out.println(c1.call());
Callable<String> c2 = ()->{return "muxiaonong2";};
System.out.println(c2.call());
// Omit when the logic is simple {} and return
Callable<String> c3 = ()->"muxiaonong3";
System.out.println(c3.call());
}

Two 、Lambda Features of expressions

  • Functional programming
  • Parameter types are automatically inferred
  • Less code , concise

3、 ... and 、Lambda Expression case

List of implementations :

​ ()->{}
​ ()->{System.out.println(1);}
​ ()->System.out.println(1)
​ ()->{return 100;}
​ ()->100
​ ()->null
​ (int x)->{return x+1;}
​ (int x)->x+1
​ (x)->x+1
​ x->x+1

Case study 1: Thread implementation :

 public static void main(String[] args) {
// Anonymous inner class mode
new Thread(new Runnable() {
@Override
public void run() {
System.out.println("runing1..........");
}
});
//Lambda Expression method
new Thread(() -> {System.out.println("runing2.....");}).start();
}

Case study 2: Collection traversal implementation

 public static void main(String[] args) {
List<String> list = Arrays.asList("java","python","scala","javascript");
// Common anonymous inner class mode
Collections.sort(list, new Comparator<String>() {
@Override
public int compare(String o1, String o2) {
return o1.length() - o2.length();
}
});
//Lambda The way
Collections.sort(list,(a,b) -> a.length() - b.length());
list.forEach(System.out::println);
}

Four 、Lambda Application scenarios of expressions

Important things are to be repeated for 3 times : There's a function interface anywhere * 3

What is a functional interface : There is only one abstract method (Object Except for methods in the class ) Is a functional interface

5、 ... and 、Lambda Expressions are used in practice

5.1 Nonparametric entity class simulation

Simulate the database connection layer :

@FunctionalInterface
public interface StudentDao {
void insert(Student student);
}

Entity class

/** @Author mxn
* @Description Student entity
* @Date 10:19 2020/11/7
* @Param
* @return
**/
public class Student {
}
 public static void main(String[] args) {
StudentDao sd1 = new StudentDao() {
@Override
public void insert(Student student) {
System.out.println(" Insert students 1");
}
};
StudentDao sd2 = (student)->{
System.out.println("student: "+student);
};
StudentDao sd3 = (Student student)-> System.out.println("student3:"+student);
sd1.insert(new Student()); // Output Insert students 1
sd2.insert(new Student());// Output
sd3.insert(new Student());// Output
}

5.2 Parameter entity class simulation

Entity class

/** @Author mxn
* @Description
* @Date 10:26 2020/11/7
* @Param
* @return
**/
public class Teacher {
}

Interface Emulation Layer

@FunctionalInterface
public interface TeacherDao {
int get(Teacher teacher);
}

Implementation layer

 public static void main(String[] args) {
TeacherDao td1 = new TeacherDao() {
@Override
public int get(Teacher teacher) {
return 1;
}
};
TeacherDao td2 = (teacher)->{return 2;};
TeacherDao td3 = (Teacher teacher)->{return 3;};
TeacherDao td4 = (teacher)->4;
TeacherDao td5 = (Teacher teacher)->5;
System.out.println(td1.get(new Teacher()));// Output 1
System.out.println(td2.get(new Teacher()));// Output 2
System.out.println(td3.get(new Teacher()));// Output 3
System.out.println(td4.get(new Teacher()));// Output 4
System.out.println(td5.get(new Teacher()));// Output 5
}

6、 ... and 、 Functional interface

Supplier: Represents an output
Consumer: Represents an input
BiConsumer: Represents two inputs
Function: Represents an input , An output ( General input and output are different types )
UnaryOperator: Represents an input , An output ( Input and output are of the same type )
BiFunction: Represents two inputs , An output ( General input and output are different types )
BinaryOperator: Represents two inputs , An output ( Input and output are of the same type )

stay Java Provides a series of functional interfaces , The logic used to accept subsequent inputs , But there are requirements for input and output

6.1 Supplier: Represents an output

 Supplier<String> s1 = ()->{return "muxiaonong";};
Supplier<String> s2 = ()->"muxiaonong2";
System.out.println(s1.get());// Output muxiaonong
System.out.println(s2.get());// Output muxiaonong2

6.2 Consumer: Represents an input

 Consumer<String> c11 = (str) -> System.out.println(str);
c11.accept("beijing");// Output beijing

6.3 BiConsumer: Represents two inputs

 BiFunction<String,String,Integer> bf = (a,b)->a.length()+b.length();
System.out.println(bf.apply(" prosperous ", " Tonight to eat chicken "));// Output a string length 8

6.4 Function: Represents an input , An output

// Function<String,Integer> Used to receive the implementation of the following function , There must be an input (String) There's an output (Integer)
Function<String,Integer> f1 = (str)->{return str.length();};
System.out.println(f1.apply("abcdefg"));// Output length 7

7、 ... and 、 Method reference

  • A method reference is an existing method or construction method used to directly access a class or instance , Method references provide a way to reference without executing methods , If the implementation of an abstract method happens to be implemented by calling another method , It is possible to use method references

7.1 Classification of method references

type grammar Corresponding lambda expression
Static method reference Class name ::staticMethod (args) -> Class name .staticMethod(args)
Instance method reference inst::instMethod (args) -> inst.instMethod(args)
Object method reference Class name ::instMethod (inst,args) -> Class name .instMethod(args)
Construction method reference Class name ::new (args) -> new Class name (args)

7.2 Static method reference

  • Static method reference : If the implementation of a functional interface can happen through Call a static method To achieve , Then you can use static method references

/**
* @program: lambda
* @ClassName Test2
* @description:
* @author: muxiaonong
* @create: 2020-10-28 22:15
* @Version 1.0
**/
public class Test2 {
// Nonparametric static methods
static String put(){
System.out.println("put.....");
return "put";
}
// Parametric static methods
public static void getSize(int size){
System.out.println(size);
}
// Ginseng Static methods with return values
public static String toUpperCase(String str){
return str.toUpperCase();
}
// Two into the refs , A return value static method
public static Integer getLength(String str,String str2){
return str.length()+str2.length();
}
public static void main(String[] args) {
// Nonparametric static methods - Normal call
System.out.println(put());// Output put
// Nonparametric static methods - Native call
Supplier<String> s1 = ()-> Test2.put();
System.out.println(s1.get());// Output put
// Nonparametric static methods - Static method reference
Supplier<String> s2 = Test2::put;
System.out.println(s2.get());// Output put
// Nonparametric static methods - Inner class calls
Supplier<String> s3 = Fun::hehe;
System.out.println(s3.get()); // Output hehe
// Parametric static methods - Static method reference
Consumer<Integer> c1 = Test2::getSize;
Consumer<Integer> c2 = (size)-> Test2.getSize(size);
c1.accept(123);
c2.accept(111);
// Static methods with parameters and return values
Function<String,String> f1 = (str)->str.toUpperCase();
Function<String,String> f2 = (str)-> Test2.toUpperCase(str);
Function<String,String> f3 = Test2::toUpperCase;
Function<String,String> f4 = Test2::toUpperCase;
System.out.println(f1.apply("abc"));// Output ABC
System.out.println(f2.apply("abc"));// Output ABC
System.out.println(f3.apply("abc"));// Output ABC
System.out.println(f4.apply("abc"));// Output ABC
// Two parameters A return value Functional interface
BiFunction<String,String,Integer> bf = (a, b)->a.length()+b.length();
BiFunction<String,String,Integer> bf2 = Test2::getLength;
System.out.println(bf2.apply("abc", "def"));// Output 6
System.out.println(bf.apply("abc", "def"));// Output 6
}
// Inner class
class Fun {
public static String hehe(){
return "hehe";
}
public static String toUpperCase(String str){
return str.toUpperCase();
}
}
}

7.3 Instance method reference

  • Instance method reference : If the implementation of functional interface can be realized by calling the instance method of an instance , Then you can use the instance method to reference
public class Test3 {
// Example no parameter method
public String put(){
return "put...";
}
// The example has the parameter method
public void getSize(int size){
System.out.println("size:"+size);
}
// The instance has a return value method
public String toUpperCase(String str){
return str.toUpperCase();
}
public static void main(String[] args) {
// Instance no parameter method returns - Normal call
System.out.println(new Test3().put());// Output put...
Supplier<String> s1 = ()->new Test3().put();
Supplier<String> s2 = ()->{return new Test3().put();};
Supplier<String> s3 = new Test3()::put;
System.out.println(s1.get());// Output put...
System.out.println(s2.get());// Output put...
System.out.println(s3.get());// Output put...
// The only way to create one test3 object
Test3 test = new Test3();
Consumer<Integer> c1 = (size)->new Test3().getSize(size);
Consumer<Integer> c2 = new Test3()::getSize;
Consumer<Integer> c3 = test::getSize;
c1.accept(123);// Output size:123
c2.accept(123);// Output size:123
c3.accept(123);// Output size:123
Function<String,String> f1 = (str)->str.toUpperCase();
Function<String,String> f2 = (str)->test.toUpperCase(str);
Function<String,String> f3 = new Test3()::toUpperCase;
Function<String,String> f4 = test::toUpperCase;
System.out.println(f1.apply("abc"));// Output ABC
System.out.println(f2.apply("abc"));// Output ABC
System.out.println(f3.apply("abc"));// Output ABC
System.out.println(f4.apply("abc"));// Output ABC
}
}

7.4 Object method reference

  • Object method reference : The first parameter type of an abstract method happens to be the type of the instance method , The remaining parameters of the abstract method can be used as parameters of the instance method . If the implementation of functional interface can be realized by the instance method call mentioned above , Then you can use object method references
/** @Author mxn
* @Description //TODO Object method reference
* @Date 14:26 2020/11/7
* @Param
* @return
**/
public class Test4 {
public static void main(String[] args) {
Consumer<Too> c1 = (too)->new Too().foo();
c1.accept(new Too());// Output foo
Consumer<Too> c2 = (Too too) ->new Too2().foo();
c2.accept(new Too());// Output foo---too2
Consumer<Too> c3 = Too::foo;
c3.accept(new Too());// Output foo
BiConsumer<Too2,String> bc = (too2,str)->new Too2().show(str);
BiConsumer<Too2,String> bc2 = Too2::show;
bc.accept(new Too2(),"abc");
bc2.accept(new Too2(),"def");
BiFunction<Exec,String,Integer> bf1 = (e,s)->new Exec().test(s);
bf1.apply(new Exec(),"abc");
BiFunction<Exec,String,Integer> bf2 = Exec::test;
bf2.apply(new Exec(),"def");
}
}
class Exec{
public int test(String name){
return 1;
}
}
class Too{
public Integer fun(String s){
return 1;
}
public void foo(){
System.out.println("foo");
}
}
class Too2{
public Integer fun(String s){
return 1;
}
public void foo(){
System.out.println("foo---too2");
}
public void show(String str){
System.out.println("show ---too2"+str);
}
}

7.5 Construction method reference

  • Construction method reference : If the implementation of functional interface can be realized by calling the constructor of a class , Then you can use the constructor to reference
/** @Author mxn
* @Description //TODO Construction method reference
* @Date 14:27 2020/11/7
* @Param
* @return
**/
public class Test5 {
public static void main(String[] args) {
Supplier<Person> s1 = ()->new Person();
s1.get();// Output Call parameterless constructor
Supplier<Person> s2 = Person::new;
s2.get();// Output Call parameterless constructor
Supplier<List> s3 = ArrayList::new;
Supplier<Set> s4 = HashSet::new;
Supplier<Thread> s5 = Thread::new;
Supplier<String> s6 = String::new;
Consumer<Integer> c1 = (age)->new Account(age);
Consumer<Integer> c2 = Account::new;
c1.accept(123);// Output age Parameter construction 123
c2.accept(456);// Output age Parameter construction 456
Function<String,Account> f1 = (str)->new Account(str);
Function<String,Account> f2 = Account::new;
f1.apply("abc");// Output str Parameter construction abc
f2.apply("def");// Output str Parameter construction def
}
}
class Account{
public Account(){
System.out.println(" Call parameterless constructor ");
}
public Account(int age){
System.out.println("age Parameter construction " +age);
}
public Account(String str){
System.out.println("str Parameter construction " +str);
}
}
class Person{
public Person(){
System.out.println(" Call parameterless constructor ");
}
}

8、 ... and 、 Summary

  • JAVA 8 introduce Lambda Expressions are ideas that receive functional programming languages , Compared with instruction programming , Functional programming emphasizes that the calculation of functions is more important than the execution of instructions .
  • lambda Expressions can make code look simple , But to some extent, it increases the readability of the code and the complexity of debugging , So in the use of the team should try to be familiar with the use of , Or don't use it at all , Otherwise, it will be more painful to maintain , That's all for today's little knowledge , If you have any questions, you can leave a message below , You come on !
版权声明
本文为[Small herdsman]所创,转载请带上原文链接,感谢

  1. 【计算机网络 12(1),尚学堂马士兵Java视频教程
  2. 【程序猿历程,史上最全的Java面试题集锦在这里
  3. 【程序猿历程(1),Javaweb视频教程百度云
  4. Notes on MySQL 45 lectures (1-7)
  5. [computer network 12 (1), Shang Xuetang Ma soldier java video tutorial
  6. The most complete collection of Java interview questions in history is here
  7. [process of program ape (1), JavaWeb video tutorial, baidu cloud
  8. Notes on MySQL 45 lectures (1-7)
  9. 精进 Spring Boot 03:Spring Boot 的配置文件和配置管理,以及用三种方式读取配置文件
  10. Refined spring boot 03: spring boot configuration files and configuration management, and reading configuration files in three ways
  11. 精进 Spring Boot 03:Spring Boot 的配置文件和配置管理,以及用三种方式读取配置文件
  12. Refined spring boot 03: spring boot configuration files and configuration management, and reading configuration files in three ways
  13. 【递归,Java传智播客笔记
  14. [recursion, Java intelligence podcast notes
  15. [adhere to painting for 386 days] the beginning of spring of 24 solar terms
  16. K8S系列第八篇(Service、EndPoints以及高可用kubeadm部署)
  17. K8s Series Part 8 (service, endpoints and high availability kubeadm deployment)
  18. 【重识 HTML (3),350道Java面试真题分享
  19. 【重识 HTML (2),Java并发编程必会的多线程你竟然还不会
  20. 【重识 HTML (1),二本Java小菜鸟4面字节跳动被秒成渣渣
  21. [re recognize HTML (3) and share 350 real Java interview questions
  22. [re recognize HTML (2). Multithreading is a must for Java Concurrent Programming. How dare you not
  23. [re recognize HTML (1), two Java rookies' 4-sided bytes beat and become slag in seconds
  24. 造轮子系列之RPC 1:如何从零开始开发RPC框架
  25. RPC 1: how to develop RPC framework from scratch
  26. 造轮子系列之RPC 1:如何从零开始开发RPC框架
  27. RPC 1: how to develop RPC framework from scratch
  28. 一次性捋清楚吧,对乱糟糟的,Spring事务扩展机制
  29. 一文彻底弄懂如何选择抽象类还是接口,连续四年百度Java岗必问面试题
  30. Redis常用命令
  31. 一双拖鞋引发的血案,狂神说Java系列笔记
  32. 一、mysql基础安装
  33. 一位程序员的独白:尽管我一生坎坷,Java框架面试基础
  34. Clear it all at once. For the messy, spring transaction extension mechanism
  35. A thorough understanding of how to choose abstract classes or interfaces, baidu Java post must ask interview questions for four consecutive years
  36. Redis common commands
  37. A pair of slippers triggered the murder, crazy God said java series notes
  38. 1、 MySQL basic installation
  39. Monologue of a programmer: despite my ups and downs in my life, Java framework is the foundation of interview
  40. 【大厂面试】三面三问Spring循环依赖,请一定要把这篇看完(建议收藏)
  41. 一线互联网企业中,springboot入门项目
  42. 一篇文带你入门SSM框架Spring开发,帮你快速拿Offer
  43. 【面试资料】Java全集、微服务、大数据、数据结构与算法、机器学习知识最全总结,283页pdf
  44. 【leetcode刷题】24.数组中重复的数字——Java版
  45. 【leetcode刷题】23.对称二叉树——Java版
  46. 【leetcode刷题】22.二叉树的中序遍历——Java版
  47. 【leetcode刷题】21.三数之和——Java版
  48. 【leetcode刷题】20.最长回文子串——Java版
  49. 【leetcode刷题】19.回文链表——Java版
  50. 【leetcode刷题】18.反转链表——Java版
  51. 【leetcode刷题】17.相交链表——Java&python版
  52. 【leetcode刷题】16.环形链表——Java版
  53. 【leetcode刷题】15.汉明距离——Java版
  54. 【leetcode刷题】14.找到所有数组中消失的数字——Java版
  55. 【leetcode刷题】13.比特位计数——Java版
  56. oracle控制用户权限命令
  57. 三年Java开发,继阿里,鲁班二期Java架构师
  58. Oracle必须要启动的服务
  59. 万字长文!深入剖析HashMap,Java基础笔试题大全带答案
  60. 一问Kafka就心慌?我却凭着这份,图灵学院vip课程百度云