复合lambda表达式

复习:

public static void main(String[] args) {
		List<Apple> list=new ArrayList<Apple>();
		//java8之前做法
		Collections.sort(list, new Comparator<Apple>() {
			public int compare(Apple o1, Apple o2) {
				return o1.getColor().compareTo(o2.getColor());
			}
		});
		//用lambda表达式
		Collections.sort(list,(Apple first,Apple second)->first.getColor().compareTo(second.getColor()));
		//因为编译器会自动根据代码上下文推测出数据类型因此
		Collections.sort(list,(first, second)->first.getColor().compareTo(second.getColor()));
		//compartor 有一个静态方法辅助方法 comparing 可以接受一个Function
		list.sort(Comparator.comparing((Apple apple)->apple.getColor()));
		//方法引用
		list.sort(Comparator.comparing(Apple::getColor));
	}


一,比较器复合

	List<Apple> list=new  ArrayList<Apple>();
		//比较器复合
		list.sort(Comparator.comparing(Apple::getColor));
		//反转
		list.sort(Comparator.comparing(Apple::getColor).reversed());
		//不仅根据颜色排序,如果遇到同种颜色根据重量排序
		list.sort(Comparator.comparing(Apple::getColor).reversed().thenComparing(Apple::getWeight));

二,谓语复合

	//第一个条件
		Predicate<Apple> predicate=(Apple apple)->apple.getWeight()>10;
//		后续条件  其中negate 是取反的意思  and 是并  or是或
		Predicate<Apple> unityPredicate=predicate.negate().and((Apple apple)->"red".equals(apple.getColor())).or((Apple apple)->"blue".equals(apple.getColor()));
		//进行过滤
		list.stream().filter(unityPredicate).collect(Collectors.toList());
三,函数复合
<span style="white-space:pre">		</span>//操作1
		Function<Apple,Integer> function1=(Apple apple)->apple.getWeight()+10;
		//操作2
		Function<strong><Integer,Integer></strong> function2=(Integer apple)->apple*12;
		//先对苹果进行加重10,再进行乘重12
		Function<Apple,Integer> unityFunction1=function1.andThen(function2);
		//同样是苹果进行加重10,再进行乘重12  compose刚好和andThen执行过程相反
		Function<Apple,Integer> unityFunction2=function2.compose(function1);
		
		list.stream().map(unityFunction1).collect(Collectors.toList());
请注意: 高亮部分的泛型 能和操作1的相同的么? 为什么?

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值