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);
總結
- lambda 表達式在java中也稱為閉包或匿名函數;
- lambda表達式 在編譯器内部會被編譯成私有方法;
- lambda 外部變量,不能修改,隻能通路。
Lambda 的初步認識
Lambda結合forEach, stream()等新特性使代碼更加簡潔!
github部落格清單位址
github歡迎關注公衆号,檢視更多内容 :