• 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
  • 相关阅读:
    OpenAI政变背后是科学家创始人的悲歌
    栈和队列及表达式求值问题
    [附源码]Python计算机毕业设计Django海南与东北的美食文化差异及做法的研究展示平台
    RabbitMQ安装与配置
    SQL语句创建数据库
    Git笔记——2
    知识蒸馏 | YOLOv7知识蒸馏实战篇 | 2/2*
    Map集合中,当添加一个键值对元素时,HashMap发生了什么?
    【集合】如果初始化HashMap,传一个17的值,它会怎么处理?
    yum clean all提示“无法从 /var/lib/rpm 打开软件包数据库”
  • 原文地址:https://blog.csdn.net/weixin_38879931/article/details/126198388