java8新特性-------------lambda 基礎語法


import java.util.Comparator;
import java.util.function.Consumer;

/**
 * create gl 
 *  lambda 基礎語法
 *
 *     ->  箭頭操作符或lambda操作符
 *    左側: lambda 表達式的參數列表
 *    右側: lambda表達式中所需執行的功能,即lambda體
 *    需要函數式接口的支持,一個接口下只有一個方法,可以使用註解 @FunctionalInterface 修飾,可以檢查是否是函數式接口
 *
 *     橫批:能省則省
 *    上聯:左右遇一括號省
 *    下聯:左側推斷類型省
 **/
public class Test01 {


    /**
     * 無參數,無返回值
     *  () -> System.out.println("666")
     */
    public static void test1(){
       int a=0; //jdk1.8以前 必須申明爲 final ,現在默認是final

       Runnable runnable=new Runnable() {
           @Override
           public void run() {
               System.out.println("666:"+a);
           }
       };
       runnable.run();
       System.out.println("---------------------------------------");

       Runnable runnable1= () -> System.out.println(777);
       runnable1.run();
    }

    /**
     * 有一個參數,無返回值
     *  (x) -> System.out.println(x)  只有一個參數 小括號可以不寫
     */
    public static void test2(){
//        Consumer consumer = (x) -> System.out.println(x);
          Consumer consumer = x -> System.out.println(x);
          consumer.accept("888");
    }


    /**
     * 有多個參數,有返回值,並且lambda 體中有多個語句,需用大括號,如果只有一條語句,則 return和大括號可以不寫
     * 參數列表的數據類型可以省略不寫,因爲jvm有類型推斷
     * @return
     */
    public static void test3(){
//        Comparator<Integer> comparator = (x,y) -> {
//            System.out.println("666");
//            return Integer.compare(x,y);
//        };
        Comparator<Integer> comparator = (x,y) -> Integer.compare(x,y);
        System.out.println(comparator.compare(5,9));
    }

    /**
     * 需求:對一個數進行運算
     */
    public static void test4(){
        Integer operation = operation(100, x -> x * x);
        System.out.println(operation);
    }

    public static Integer operation(Integer num,Myfun myfun){
        return myfun.getValue(num);
    }

    public static void main(String[] args) {
//        test1();
//        test2();
//        test3();
        test4();
    }

}


@FunctionalInterface
public interface Myfun {
    Integer getValue(Integer num);
}





發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章