java8_Lambda

Lambda

  • function包,提供lambda接口
        public interface Function<T, R> {
            /**
             * Applies this function to the given argument.
             *
             * @param t the function argument
             * @return the function result
             */
            R apply(T t);
        
            default <V> Function<V, R> compose(Function<? super V, ? extends T> before) {
                Objects.requireNonNull(before);
                return (V v) -> apply(before.apply(v));
            }
            ...
        }
    
  • 除了default修飾的方法外,接口中只能有一個方法apply,這也是使用lambda接口的必要條件。
    表示給定一個輸入T,返回一個輸出R,使用lamdba接口時,我們使用表達式來表示實現接口的唯一方法apply()
        Function<Integer,Integer> function = (x)->{
          System.out.println("x : "+ String.valueof(x));
          return x+10;
        };
    

Lambd 兩種表現形式

  • 定義源
      List<String> list = Arrays.asList ("a", "c", "A", "C");
    
  • lambda表達式的另一種表現形式爲 lambda方法引用
        1)
        list.sort (String::compareToIgnoreCase);
        2)
        Predicate<String> p = String::isEmpty;
        3)
        Function<String, Integer> f1 = (String a) -> {return Integer.valueOf (a);};
        Integer result = f1.apply ("2");
    
    
  • 函數編程,會被編譯成一個函數式接口。
        1)
        list.sort ((s1, s2) -> s1.compareToIgnoreCase (s2));
        2)
        Predicate<String> q = (String a) -> {
            return a.isEmpty ();
        };
        3)
        Function<String, Integer> f2 = Integer::valueOf;
        // Function中的泛型 String代表返回類型,Integer代表輸入類型,在lambda引用中會根據泛型來進行類型推斷。
        Integer result = f2.apply ("2");
    

Lambda 用途

  • 只有一個抽象方法的函數式接口
     new Thread(new Runnable() {
       @Override
       public void run(){
          System.out.println("t1");
       } 
     }).start();
     
     new Thread( () -> run("t2") ).start();
     new Thread( () -> {
       Integer a = 2;
       System.out.println(a);
     }).start();
    
  • 集合批量操作
        public class listLambda {
            public static void main(String[] args) {
                List<String> list = Arrays.asList("a","b","b");
                //foreach
                for (String  s : list
                     ) {
                    System.out.println(s);
                }
                System.out.println("-----------------");
                //lambda  用Iterable.forEach()取代foreach loop
                list.forEach((e) -> System.out.println(e));
            }
        }
    
  • 流操作
        public class listLambda {
            public static void main(String[] args) {
                List<String> list = Arrays.asList("a","b","b");
                System.out.println(list.stream().filter((e) -> "b".equals(e)).count());
            }
        }
    

參考例子

 //在map集合下的使用
      Map<String,Object> map =new HashMap<String, Object>();
      map.put("A",1);
      map.put("B",2);
      //需要添加判斷條件的
      map.keySet().forEach(name ->{
          if(name.startsWith("A")){
             System.out.println(map.get(name));
          }
      });
      System.out.println("-----------------------------------------");
      //不需要判斷條件
      map.keySet().forEach(name ->{
            System.out.println(map.get(name));
      });
      //方法引用由::雙冒號操作符標示
      System.out.println("-----------------------------------------");
      map.keySet().forEach( System.out::println);

      // list
      List future = Arrays.asList("Great works are accomplished not by strength but by perseverance.","Keep its original intention and remain unchanged");
      //lambda
      future.forEach(n -> System.out.println(n));
      //lambda 結合 方法引用
      future.forEach(System.out::println);

總結

  1. lambda 表達式在java中也稱爲閉包或匿名函數;
  2. lambda表達式 在編譯器內部會被編譯成私有方法;
  3. lambda 外部變量,不能修改,只能訪問。
    image
    image
    image

Lambda結合forEach, stream()等新特性使代碼更加簡潔!

github博客列表地址

github
歡迎關注公衆號,查看更多內容 :
XG54_9_WXMH_5X_HB_H_7V

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