zoukankan      html  css  js  c++  java
  • 从C#到Java(lambda比较)

    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拼接到当前表达式前。

  • 相关阅读:
    Python——python读取html实战,作业7(python programming)
    Python——python读取html实战,作业7(python programming)
    Python——python读取xml实战,作业6(python programming)
    Python——python读取xml实战,作业6(python programming)
    二分查找(c &amp; c++)
    大型站点技术架构(八)--站点的安全架构
    Android MTP 文件浏览Demo
    HDU2037 事件排序问题
    折腾开源WRT的AC无线路由之路-3
    启动VIP报CRS-1028/CRS-0223致使VIP状态为UNKNOWN故障分析与解决
  • 原文地址:https://www.cnblogs.com/LvJiaXuanBlogs/p/10475471.html
Copyright © 2011-2022 走看看