条件组合
- Comparator的组合
接着上一节,排序问题,我们可以组合多个条件进行排序:
studentQueryService.getStudentList().sort(comparingDouble(Student::getAvgScore))
.reversed() //倒叙排
.thenComparing(Student::getAge() //当有相同的平均分时,按照年龄再排序
- Predicate的组合
找到平均分>75并且(名字中含有“李”或者年龄>8)
@Test
public void testFilterByStreaming(){
Predicate<Student> predicate = (s) -> s.getAvgScore() > 75;
predicate.and( s -> s.getCnName().indexOf("李")!=-1)
.or(s -> s.getAge() > 8);
}
- Function<T, R>的组合
@Test
public void testFunctionCompose(){
Function<Integer, Integer> f = (x) -> x + 1;
Function<Integer, Integer> g = x -> x * 2;
Function<Integer, Integer> h = f.andThen(g); //g(f(x)) = (3 + 1) * 2 = 8
Function<Integer, Integer> h1 = f.compose(g); //f(g(x)) = (3 * 2) + 1 = 7
System.out.println(f.apply(3) + ", " + g.apply(3) + ", " + h.apply(3) + ", " + h1.apply(3));
}