• 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
  • 相关阅读:
    竞赛 深度学习猫狗分类 - python opencv cnn
    Pycharm2024版,更换安装源
    WPF .NET 7.0学习整理(一)
    【贪心算法】独木舟上的旅行
    Mac系统配置k8s completion命令补全
    C++宏函数和内联函数
    【JAVA】06 封装、继承、多态 总结(初级)
    Linux的常用指令用法
    怎么看出 Java 的 Comparator是升序还是降序
    产品网站的FAQ页面该如何编辑?
  • 原文地址:https://blog.csdn.net/weixin_38879931/article/details/126198388