• java8 lambda表达式和双冒号 :: 使用


    举个例子
    假设你有一个Apple类,它有一个getColor方法,还有一个变量inventory保存着一个Apples的列表。你可能想要选出所有的绿苹果,并返回一个列表。通常我们用筛选(filter)一词来表达这个概念。在Java 8之前,你可能会写这样一个方法filterGreenApples:

    public static List<Apple> filterGreenApples(List<Apple> inventory){ 
     	List<Apple> result = new ArrayList<>(); 
     	for (Apple apple: inventory){ 
     		if ("green".equals(apple.getColor())) {
     			result.add(apple); 
     		} 
     	} 
     	return result; 
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9

    接下来,我们对代码做简单的调整,引入一个判断的接口,专门对 if 后边的判断做处理

    public interface Predicate<T>{
    	boolean test(T t);
    }
    
    • 1
    • 2
    • 3

    有了这个以后,我们的筛选方法就可以这么写

    public static List<Apple> filterGreenApples(List<Apple> inventory,Predicate<Apple> predicate){ 
     	List<Apple> result = new ArrayList<>(); 
     	for (Apple apple: inventory){ 
     		if (predicate.test(apple)) {
     			result.add(apple); 
     		} 
     	} 
     	return result; 
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9

    接下来,我们准备调用筛选苹果的方法,以前我们可以使用匿名内部类的方法例如:

    	List<Apple> resultList = t.filter(appleList, new Predicate<Apple>() {
             @Override
             public boolean test(Apple apple) {
                 return "green".equals(apple.getColor());
             }
         })
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6

    然而,在java8后,可以对以上代码进行lambda优化,优化后:

    List<Apple> resultList = t.filter(appleList, apple -> "green".equals(apple.getColor()));
    
    • 1

    后边匿名内部类,变成了一行lambda表达式,是不是简单了许多。
    如果此时,我们在Apple中再次调整,增加一个 static 静态方法进行判断,将会变成以下的样子

     public static boolean isGreen(Apple apple){
            return "green".equals(apple.getColor());
     }
    
    • 1
    • 2
    • 3

    使用类中将会这么写

    List<Apple> resultList = t.filter(appleList, apple -> Apple.isGreen(apple));
    // java8对于这种static的方法调用,还提供了另外的写法
    List<Apple> resultList = t.filter(appleList, Apple::isGreen);
    // 上边两行效果相同
    
    • 1
    • 2
    • 3
    • 4
  • 相关阅读:
    linux安装mysql
    React的Render的简单实现
    Django笔记十一之外键查询优化select_related和prefetch_related
    小样本学习(2)--LibFewShot使用
    封装Detours用于Python中x64函数hook
    import关键字的使用
    基于单片机的机械臂运行轨迹在线控制系统设计
    【毕业设计】天气数据分析系统 - python 大数据
    利用爬虫技术自动化采集汽车之家的车型参数数据
    SEM 与 SEO 之间的区别与联系
  • 原文地址:https://blog.csdn.net/weixin_38879931/article/details/126198388