3.8 复合Lambda表达式的有用方法

Comparator、Predicate和Function提供了复合的方法,允许将多个简单的Lambda表达式组合,构成复杂逻辑应用。

3.8.1 比较器复合

逻辑语义 方法 示例语义 代码
逆序 Comparator#reversed 按苹果重量降序排列 inventory.sort(Comparator.comparing(Apple::getWeight));
比较器链 Comparator#thenComparing 先按苹果重量升序,再按苹果颜色字典序升序排列 inventory.sort(Comparator.comparing(Apple::getWeight).thenComparing(Apple::getColor));

3.8.2 谓词复合

逻辑语义 方法 示例语义 代码
Predicate#negate 不是红苹果 Predicate<Apple> nonRedApplePredicate = redApplePredicate.negate();
Predicate#and 超过150g的红苹果 Predicate<Apple> redHeavyApples = redApplePredicate.and(a -> a.getWeight() > 150);
Predicate#or 超过150g的红苹果或者超过200g的苹果 Predicate<Apple> nonRedApples = redApples.negate();

3.8.3 函数复合

逻辑语义 方法 示例
g(f(x))
(g∘ f)(x)
Function#andThen Function<Integer, Integer> m = f.andThen(g);
m.apply(1); // 4
f(g(x))
(f∘ g)(x)
Function#compose Function<Integer, Integer> n = f.compose(g);
n.apply(1); // 3
Function<Integer, Integer> f = x -> x + 1;
Function<Integer, Integer> g = x -> x * 2;

更具体的示例,一封信基于抬头、拼写检查、落款构造。

public class Letter {
    public static String addHeader(String text) {
        return "From Raoul, Mario and Alan: " + text;
    }

    public static String addFooter(String text) {
        return text + " Kind regards";
    }

    public static String checkSpelling(String text) {
        return text.replaceAll("labda", "lambda");
    }

    public static void main(String[] args) {
        Function<String, String> addHeader = Letter::addHeader;
        Function<String, String> transformationPipeline =
            addHeader.andThen(Letter::checkSpelling).andThen(Letter::addFooter);
    }
}
posted @ 2023-06-28 17:48  蒋智  阅读(9)  评论(0)    收藏  举报