学会-Java8 Lambda 复合使用

189 阅读2分钟

Lambda

复合使用

比较器复合

Comparator接口存在 逆序方法reversed() 和 比较器链thenComparing()

List<Employee> employees = EmployeeData.getEmployees();
// 以员工的工资排序
Comparator<Employee> comparator = Comparator.comparing(Employee::getSalary);
employees.sort(comparator);
employees.stream().forEach(System.out::println);
// 逆序排序
employees.sort(comparator.reversed());
employees.stream().forEach(System.out::println);
// 出现工资一样的以名称排序
employees.sort(comparator.reversed().thenComparing(Employee::getName));
employees.stream().forEach(System.out::println);

谓词复合

Predicate接口and、or和negate

and和or方法是按照在表达式链中的位置,从左向右确定优先级的。因此,a.or(b).and(c)可以看作(a || b) && c。同样,a.and(b).or(c) 可以看作(a && b) || c。

Predicate<Employee> predicate = employee -> employee.getSalary() > 30000;

// &&
Predicate<Employee> and = predicate.and(employee -> employee.getId() == 2222);

// ||
Predicate<Employee> or = predicate.or(employee -> employee.getSalary() < 100);

// 非
Predicate<Employee> negate = predicate.negate();

函数复合

Function接口andThen和compose方法

image-1
image-1
public class Letter {

    public static String addHeader(String text){
        System.out.println("addHeader:" +System.nanoTime());
        return "header"+text;
    }

    public static String addFooter(String text){
        System.out.println("addFooter:"+System.nanoTime());
        return "Footer"+text;
    }

    public static String check(String text){
        System.out.println("check:"+System.nanoTime());
        return text.replace("aaa","ccc");
    }


    public static void main(String[] args) {
        Function<String,Stringfunction = Letter::addHeader;
        Function<StringString> function1 = function.andThen(Letter::addFooter).andThen(Letter::check);
        System.out.println(function1.apply("aaaabbbbaaa"));

        Function<StringString> function2 = function.compose(Letter::addFooter).compose(Letter::check);
        System.out.println(function2.apply("aaaabbbbaaa"));

    }
}