Java8(四)——复合lambda表达式

前言

Java8的好几个函数式接口都为了使用方便而设计了复合的方法,其实也就是函数接口中的默认方法。

比较器复合

所谓的比较器复合,其实也就是说明Comparator函数式接口中的default方法。具体的可以查看源码,这里就不贴出来了。这里就直接举一个实例,比如,我们已经有了一个lambda实现的比较器,但是现在我们需要进行逆序排序,难道我们需要重新建一个比较器么?并不是,java8中我们可以利用指定的复合表达式完成这个工作,直接上实例代码吧

public class UnionLambdaDemo {

    public static void main(String[] args) {
		
        List appleList = AppleContainer.initAppleList();
        compareReverse(appleList);
		
    }

    public static void compareReverse(List apples){
        System.out.println("原始数据:"+apples);
		//建立排序比较器
        Comparator weightComp = Comparator.comparing(Apple::getWeight);
        Collections.sort(apples,weightComp);
        System.out.println("正常排序:"+apples);
		
		//这里直接利用reversed完成逆序排序,不需要重新构建排序
        Collections.sort(apples,weightComp.reversed());
        System.out.println("逆序排序:"+apples);
    }
}

谓词复合

这里就是说明Predicate函数式接口中的default方法,其实能进行复合操作的原因也很简单,能进行复合的也就只有and,or,andThen等,这些都是在Predicate接口中定义的default方法。

如下所示:已经有了一个用于筛选红色苹果的谓词,但是针对这个谓词如果有新的需求,我们也不需要构建新的Predicate。

Predicate applePredicate = apple->apple.getColor().equals("red");

 完整实例:

public class UnionLambdaDemo {

    public static void main(String[] args) {
		
        List appleList = AppleContainer.initAppleList();
        predicateCombine(appleList);

    }
	
	public static void predicateCombine(List apples){
		
		//有了一个筛选红色苹果的谓词
		Predicate applePredicate = apple->apple.getColor().equals("red");

		List bigApple = filterApple(apples, applePredicate.and(apple -> apple.getWeight() > 100).or(apple -> apple.getColor().equals("green")));
		System.out.println(bigApple);
	}

    public static List filterApple(List apples,Predicate applePredicate){
        List result = new ArrayList<>();
        for (Apple apple:apples){
            if(applePredicate.test(apple)){
                result.add(apple);
            }
        }
        return result;
    }
}

输出结果:

函数复合

其实也就是Function函数式接口的复合操作,这个就两个,compose和andThen

    public static void functionCombine(int param){
        Function f = x->x+1;
        Function g = x->x*2;

        //f.andThen(g)相当于是g(f(x))
        Function r = f.andThen(g);
        int andThenResult = r.apply(param);
        System.out.println(andThenResult);//如果param是1,这里输出4

        //f.compose(g)相当于f(g(x))
        Function nr = f.compose(g);
        int composeResult = nr.apply(param);
        System.out.println(composeResult);//如果param为1,这里输出3
    }

总结

太简单了,貌似没啥可总结的,lambda的主要内容到这里就完成了,针对stream的内容,下篇博客开始

你可能感兴趣的:(Java8)