从C#到Java(lambda比较)

java8中新增的lambda和C#中的仍是比较类似的,下面用几个例子来比较一下两方经常使用的一些方法做为比较便于记忆。咱们用一个List来作比较:java

        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>app

  Consumer和Action均表示一个无返回值的委托。C#中lambda表示的是委托链,因此咱们能够像操做委托同样直接用+= -= 来操做整个lambda表达式树。在java中不支持相似的写法,因此Consumer有两个方法:appect(T) andThen(Comsumer<? super T>),appect表示执行,andThen表示把参数内的lambda加入到stream流中。
spa

        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(),都是一些逻辑判断。blog

 

        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#)的时候才会真正建立这个对象。get

4.Function和Funcit

  Function就和Func同样,传入参数,获取返回值。Function也有三个默认的方法:appect andThen compose,andThen拼接到当前表达式后,compose拼接到当前表达式前。io

相关文章
相关标签/搜索