JAVA8新特性之Lambda表達式

  1. Lambda(Lambda 是希臘字母 λ 的英文名稱)表達式本質上是一個匿名方法.也可以稱之爲閉包。該方法允許把函數作爲一個方法的參數(函數作爲參數傳遞進入方法中)。使用該表達式可以使JAVA代碼變得更加簡潔。
  2. Lambda表達式的語法
    (parameters) -> expression 或 (parameters) ->{ statements; }
  3. 特徵
    可選類型聲明:不需要聲明參數類型,編譯器可以統一識別參數值。
    可選的參數圓括號:一個參數無需定義圓括號,但多個參數需要定義圓括號。
    可選的大括號:如果主體包含了一個語句,不需要使用大括號。
    可選的返回關鍵字:如果主體只有一個表達式返回值則編譯器會自動返回值,大括號需要指明表達式返回了一個數值。
    4.Lambda表達式的幾種格式
    1. ()->5 :不需要參數,返回值爲5
    2. x->2*x :需要參數,返回值爲輸入值的2倍。
    3. (x,y)->x-y:接受2個參數,並且返回差值。
    4. (int x,int y) ->x+y:接受兩個int型的整數,返回他們的和。
    5. (String s)->System.out.println(s) :接受一個String對象,並在控制檯打印,不返回任何值。
      因此可以總結出Lambda的表達式的格式是:
      (params,params) -> {your Code}
      params:參數;result:返回值;your Code你自己的代碼
      5.Lambda表達式示例
    6. 替換靜態內部類:
      JAVA7的時候我們使用多線程使用靜態內部類如下:
public static void OldRunnable(){
        new Thread(new Runnable() {
            @Override
            public void run() {
                System.out.println("old runnable !");
            }
        }).start();
    }

這裏的代碼就會比較多,不是很簡潔,那麼如果我們使用Lambda的語法格式重寫。如下:

 public static void newRunnable(){
        new Thread(()->System.out.println( "New Runnable , name is "+Thread.currentThread().getName())).start();
    }

使用Lambda表達式只需要一行代碼就能完成線程的創建。
2. 更加簡潔的遍歷集合:

 /**
     * 遍歷集合
     */
    public static void iteratorTest(){
        HashMap<String,String> map = new HashMap<>();
        map.put("1","11");
        map.put("2","22");
        map.put("3","33");
        map.put("4","44");
        map.forEach((k,v)-> System.out.println("key:"+k+"||V:"+v));
        System.out.println("-------------分割線----------------");
        Hashtable hashtable = new Hashtable();
        hashtable.put("x","XXX");
        hashtable.put("y","YYY");
        hashtable.put("z","ZZZ");
        hashtable.forEach((k,v)-> System.out.println("key>>>>"+k+"||value>>>>>>>"+v));
        System.out.println("-------------分割線----------------");
        ArrayList list = new ArrayList();
        list.add("張三");
        list.add("李四");
        list.add("王五");
        list.forEach(i-> System.out.println("list>>>>>"+i));
    }
  1. 結合map使用,這裏的map不是數據集合上的map,這裏的map是一個方法,將一個對象變換爲另一個對象。
/**
     * map 這裏map的作用是將一個對象變換爲另外一個
     */
    public static void mapTest(){
        List<Double> cost = Arrays.asList(10.0, 20.0,30.0);
        cost.stream().map(x->x*0.5).forEach(y-> System.out.println("cost>>>>"+y));
    }
/**
     * map轉換並且輸出線程名
     */
    public static void ThreadTest(){
        IntStream
                .range(0,5)
                .boxed()
                .map(
                        i->new Thread(()->System.out.println(Thread.currentThread().getName()))
                )
                .forEach(Thread::start);
    }
  1. 結合reduce使用,更加便捷的對集合中的數據做求和操作;reduce實現的則是將所有值合併爲一個
    public static void mapReduceTest(){
        List<Double> cost = Arrays.asList(10.0, 20.0,30.0);
        double allCost = cost.stream().reduce((sum,x)->sum+x).get();
        System.out.println("allCost>>>>"+allCost);
        System.out.println("-------------分割線----------------");
        HashMap<String,Integer> map = new HashMap<>();
        map.put("1",11);
        map.put("2",22);
        map.put("3",33);
        map.put("4",44);
        int allCostFormap= map.values().stream().reduce((sum,k)->sum+k).get();
        System.out.println("allCostFormap>>>"+allCostFormap);
    }

5.結合filter方法對結合進行刪選 ,過濾掉一部分不需要的元素

 public static void filterTest(){
        List<Double> cost = Arrays.asList(10.0, 20.0,30.0);
        List<Double> filterCost = cost.stream().filter(x->x>15.0).collect(Collectors.toList());
        filterCost.forEach(x-> System.out.println(">>>>>"+x));
        System.out.println("-------------分割線----------------");
        HashMap<String,Integer> mapBefore = new HashMap<>();
        mapBefore.put("1",11);
        mapBefore.put("2",22);
        mapBefore.put("3",33);
        mapBefore.put("4",44);

        Map<String,Integer> filterMap = mapBefore
                .entrySet()
                .stream()
                .filter(map ->map.getValue() != 11)
                .collect(Collectors.toMap( p -> p.getKey(), p -> p.getValue()));
        System.out.println(">>>>>"+filterMap);

    }
  1. 與函數式接口Predicate配合
 public static void predicateTest(){
        List<String> languages = Arrays.asList("Java","Python","scala","Shell","R");
        System.out.println("Start With s :");
        filterTest(languages,x->x.startsWith("s"));
    }

    public static void filterTest(List<String> languages, Predicate<String> condition){
        languages.stream().filter(x->condition.test(x)).forEach(x-> System.out.println(">>>>>"+x));
    }
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章