复习:
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的相同的么? 为什么?