zoukankan      html  css  js  c++  java
  • 【Java】Lambda表达式详解及实战

    jdk8新语法:

    JDK8

    JDK1.0 95 Vector Hashtable synchronized
    JDK1.2 98 List Set Map
    JDK1.5 2004 泛型 枚举 标注 多线程 自动封箱 静态导入 可变长参数(本文档有讲解)
    JDK6 Arrays.copyOf()
    JDK7 String作为switch表达式
    switch(String) --> 原理是获得字符串hashCode(int)、再做等值判断
    例如:switch("a”) { case “a” : {①} }
    ==> switch(“a”.hashCode()) { case “a”.hashCode():if(“a”.equals(“a”) {①}}

    int字面值 0b0001111(二进制表达) 分隔符(int a = 1000_000_000)
    try-with-resources Fork-Join 泛型自动推断
    JDK8 2014 lambda表达式

    Lambda表达式

    避免冗余代码, 提高程序的可重用性
    提高可重用性: 将代码的不变部分, 和可变部分 分离

    1. 继承关系
    2. 将数据作为方法的参数
    3. 将代码作为方法的参数 定义接口,通过接口回调实现
      Lambda : 函数式编程

    Lambda表达式 匿名内部类的简便写法 实现的接口必须只有一个抽象方法 (函数式接口)
    语法:

    1. (参数表) -> {代码块}
    2. (参数表) -> 表达式
      参数表中形参的类型可以省略, 由编译器自动推断
      如果参数表只有一个参数,()可以省略
    Runnable r= new Runnable(){
        public void run(){
            System.out.println("hehe");
        }
    };
    Runnable r = ()->{System.out.println("hehe");};//与上等价
    Callable<Integer> c = new Callable<Integer>(){
         public Integer call(){
            return 10;
        }
    }
    Callable<Integer> c = ()->10;//与上等价
    方法引用
    main:
            A a2 = (MyClass mc)->mc.method();
            A a3 = MyClass::method;
     
            B b2 = (MyClass mc , String s)->mc.method(s);
            B b3 = MyClass::method;
     
            C c2 = (MyClass mc,String s1,String s2)->mc.method(s1, s2);
            C c3 = MyClass::method;
     
            D d2 = ()->MyClass.staticMethod();
            D d3 = MyClass::staticMethod;
    
            E e2 = (s)->System.out.println(s);
            E e3 = System.out::println;
    	interface A { 
    	    void act(MyClass mc);
            }
    	interface B { 
                void act(MyClass mc, String s);
            }
    	interface C { 
    	    void act(MyClass mc,String s1, String s2);
            }
    	interface D { 
    	    void act();
            }
    	interface E { 
    	    void act(String s);
            }
    
    ------------------
    class MyClass {
        public void method() {
    		System.out.println(“method()”);
    	}
        public void method(String s) {
    		System.out.println(“method(String)”);
    	}
        public void method(String s, String s) {
    		System.out.println(“method(String, String)”);
    	}
        public static void staticMethod() {
    		System.out.println(“static method()”);
    	}
    }
    

    接口的新语法:

    1. 接口中可以定义默认方法 default void print(){}
    2. 接口中可以定义静态方法 static void print(){}
    3. 接口中可以定义私有方法 since JDK9

    例题在最后;

  • 相关阅读:
    第八周学习进度
    个人NABCD
    软件需求模式阅读笔记一
    问题账户需求分析
    2017年秋季个人阅读计划
    软件需求与分析——读后感
    第十六周周总结
    第十五周周总结
    第十四周周总结
    第十三周周总结
  • 原文地址:https://www.cnblogs.com/jwnming/p/13093767.html
Copyright © 2011-2022 走看看