• 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
  • 相关阅读:
    MATLAB求解夏普利值
    Simulink建模之键盘快捷方式和鼠标操作
    【Linux】部署web项目
    blender建立一个适合three.js中使用杯子/花瓶 反细分减小体积
    cutree 算法
    树模型(2)随机森林
    发送自定义广播
    万向区块链小课堂:DAO如何革新组织方式?
    java毕业设计物资租赁管理系统mybatis+源码+调试部署+系统+数据库+lw
    springboot整合logback
  • 原文地址:https://blog.csdn.net/weixin_38879931/article/details/126198388