1

在一起来学Java8(二)——Lambda表达式中我们学习了Lambda表达式的基本用法,现在来了解下复合Lambda。

Lambda表达式的的书写离不开函数式接口,复合Lambda的意思是在使用Lambda表达式实现函数式接口抽象方法后,还可以再次调用接口的其它方法,因为从Java8开始,接口中可以包含默认实现的方法。关于接口默认实现方法将会在后面章节详细阐述。

常见的复合Lambda常见的有以下几类:

  • 比较器复合,对应的函数式接口:Comparator
  • 谓词复合,对应的函数式接口:Predicate
  • 函数复合,对应的函数式接口:Function

比较器复合

先来看下Comparator接口的常见用法,针对商品价格从低到高排序

package learn.java8.ch4;

import java.util.Arrays;
import java.util.Comparator;
import java.util.List;

class Goods {
    private String name;
    private int price;

    public Goods(String name, int price) {
        super();
        this.name = name;
        this.price = price;
    }

    省略get set
}

public class ComparatorTest {

    public static void main(String[] args) {
        List<Goods> list = Arrays.asList(
                new Goods("mete30", 3999),
                new Goods("mete30 pro", 4999),
                new Goods("redmi k20", 2999),
                new Goods("iqoo", 2999),
                new Goods("iphone11", 5000)
                );
        
        Comparator<Goods> comparatorForPrice = (Goods goods1, Goods goods2) -> {
            return Integer.compare(goods1.getPrice(), goods2.getPrice());
        };
        list.sort(comparatorForPrice);
        System.out.println(list);
    }
}

这里是根据价格从低到高排序,我们可以再加一个需求,如果价格一样,再根据商品名称排序。那么代码可以这样写:

public static void main(String[] args) {
        List<Goods> list = Arrays.asList(new Goods("mete30", 3999), new Goods("mete30 pro", 4999),
                new Goods("redmi k20", 2999), new Goods("iqoo", 2999), new Goods("iphone11", 5000));

        Comparator<Goods> comparatorForPrice = (Goods goods1, Goods goods2) -> {
            return Integer.compare(goods1.getPrice(), goods2.getPrice());
        };

        Comparator<Goods> comparatorForName = (Goods goods1, Goods goods2) -> {
            return goods1.getName().compareTo(goods2.getName());
        };
        
        // 把两个函数式接口进行复合,组成一个新的接口
        Comparator<Goods> finalComparator = comparatorForPrice.thenComparing(comparatorForName);
        list.sort(finalComparator);
        System.out.println(list);
    }

上面的例子中Comparator<Goods> finalComparator = comparatorForPrice.thenComparing(comparatorForName);就是复合Lambda表达式的体现。其中thenComparing()方法是Comparator接口的一个默认实现方法。

谓词复合

谓词复合,即使用谓词函接口来实现,谓词接口定义如下:

@FunctionalInterface
public interface Predicate<T> {
  
    // 抽象接口,判断是否为真
    boolean test(T t);
    
    // 默认方法,跟另一个谓词一起判断
    default Predicate<T> and(Predicate<? super T> other) {
        Objects.requireNonNull(other);
        return (t) -> test(t) && other.test(t);
    }

    //  默认方法,判断后进行非操作
    default Predicate<T> negate() {
        return (t) -> !test(t);
    }

    // 默认方法,跟另一个谓词一起判断
    default Predicate<T> or(Predicate<? super T> other) {
        Objects.requireNonNull(other);
        return (t) -> test(t) || other.test(t);
    }
    
    static <T> Predicate<T> isEqual(Object targetRef) {
        return (null == targetRef)
                ? Objects::isNull
                : object -> targetRef.equals(object);
    }
}

下面来看下具体的例子:

package learn.java8.ch4;

import java.util.function.Predicate;

public class PredicateTest2 {
    static class Goods {
        private String name;
        // 价格
        private int price;
        // 库存
        private int storeCount;

        public Goods(String name, int price, int storeCount) {
            super();
            this.name = name;
            this.price = price;
            this.storeCount = storeCount;
        }
    }

    public static void main(String[] args) {
        Goods mete30pro = new Goods("mete30 pro", 4999, 111);
        Goods iphone11 = new Goods("iphone11", 5000, 444);

        Predicate<Goods> predicate = (goods) -> goods.price > 4000;

        System.out.println("mete30pro价格是否大于4000:" + predicate.test(mete30pro));

        Predicate<Goods> predicatePrice = (goods) -> goods.price > 6000;
        Predicate<Goods> predicateStore = (goods) -> goods.storeCount > 400;
        // 价格大于6000或库存大于400
        Predicate<Goods> predicateOr = predicatePrice.or(predicateStore);
        System.out.println("价格大于6000或库存大于400:" + predicateOr.test(iphone11));
    }

}

函数复合

函数复合使用java.util.function.Function函数式接口中来实现。

Function接口定义如下:

// 两个泛型参数,T表示入参类型,R表示返回类型
@FunctionalInterface
public interface Function<T, R> {

    // 抽象方法
    R apply(T t);

    // 默认实现方法,先执行before,将结果带入当前apply方法中执行
    default <V> Function<V, R> compose(Function<? super V, ? extends T> before) {
        Objects.requireNonNull(before);
        return (V v) -> apply(before.apply(v));
    }

    // 按顺序执行,先执行当前apply函数,再执行指定的after.apply函数
    default <V> Function<T, V> andThen(Function<? super R, ? extends V> after) {
        Objects.requireNonNull(after);
        return (T t) -> after.apply(apply(t));
    }

    // 辅助方法,始终返回入参值
    static <T> Function<T, T> identity() {
        return t -> t;
    }
}

从代码上看很容易就能看懂,接下来列举几个简单例子,首先来看下andThen方法的使用:

private static void test1() {
    Function<Integer, Integer> funMultiply = (input) -> input * 2;
    Function<Integer, Integer> funMinus = (input) -> input - 1;
    // input * 2 - 1
    Function<Integer, Integer> finalFun = funMultiply.andThen(funMinus);

    Integer result = finalFun.apply(2);
    System.out.println(result); // 3
}

这个例子中定义两个函数,一个对参数做乘法操作然后返回,一个对参数做减法操作然后返回。接着使用andThen方法把两个函数串联起来。用数学公式表示即为:2 * 2 - 1

接下来是compose例子:

private static void test2() {
    Function<Integer, Integer> funMultiply = (input) -> input * 2;
    Function<Integer, Integer> funMinus = (input) -> input - 1;

    // (input - 1) * 2
    Function<Integer, Integer> finalFun = funMultiply.compose(funMinus);

    Integer result = finalFun.apply(2);
    System.out.println(result); // 2
}

这里是先执行减法,得到的结果传入,再执行乘法操作。用数学公式表示即为:(2 - 1) * 2

https://shimo.im/docs/gGQHg8x... 《2020年最新Java架构师系统进阶资料免费领取》,可复制链接后用石墨文档 App 或小程序打开


眉目清俊
13 声望4 粉丝