java8中新增的lambda和C#中的還是比較相似的,下面用幾個例子來比較一下兩方常用的一些方法作為比較便於記憶。我們用一個List來做比較:
var list = new ArrayList<Person>(); list.add(new Person("張三", 21)); list.add(new Person("李四", 22)); list.add(new Person("王五", 22)); list.add(new Person("趙六", 24));
1.Consumer<T> 和 Action<T>
Consumer和Action均表示一個無返回值的委托。C#中lambda表示的是委托鏈,所以我們可以像操作委托一樣直接用+= -= 來操作整個lambda表達式樹。在java中不支持類似的寫法,所以Consumer有兩個方法:appect(T) andThen(Comsumer<? super T>),appect表示執行,andThen表示把參數內的lambda加入到stream流中。
list.stream().forEach(p -> System.out.println(p.getName())); Consumer<Person> action = p -> System.out.println("action" + p.getName()); list.stream().forEach(action);
list.ForEach(p => Console.WriteLine(p.Name)); Action<Person> action = p => Console.WriteLine(p.Name); list.ForEach(action);
2.Predicate 和 Func<T,bool>
predicate類似func<T .. ,bool>,返回值是bool的委托。不同的是Predicate提供了幾個默認的實現:test() and() negate() or() equals(),都是一些邏輯判斷。
list.stream().filter(p -> p.getAge().intValue() > 21).forEach(p -> System.out.println(p.getName())); list.stream().filter(myPredicate(22)).map(p -> p.getName()).forEach(System.out::printIn); public static Predicate<Person> myPredicate(int value) { return p -> p.getAge().intValue() > value; }
list.Where(p => p.Age > 22).Select(p => p.Name).ToList();
3.Supplier
supplier,這個比較特殊,有點類似於IQueryable接口,懶加載,只有在get(java)/AsEnumerable(C#)/ToList(C#)的時候才會真正創建這個對象。
4.Function和Func
Function就和Func一樣,傳入參數,獲取返回值。Function也有三個默認的方法:appect andThen compose,andThen拼接到當前表達式后,compose拼接到當前表達式前。