【小家java】java8新特性之---函数式接口(Supplier、Consumer、Predicate、Function、UnaryOperator,通往高阶设计的好工具)(下)

简介: 【小家java】java8新特性之---函数式接口(Supplier、Consumer、Predicate、Function、UnaryOperator,通往高阶设计的好工具)(下)

public interface Predicate


断言接口,有点意思了。其默认方法也封装了and、or和negate逻辑 和一个静态方法isEqual。


//and方法接收一个Predicate类型,也就是将传入的条件和当前条件以并且的关系过滤数据。
default Predicate<T> and(Predicate<? super T> other) {
    Objects.requireNonNull(other);
    return (t) -> test(t) && other.test(t);
}
//or方法同样接收一个Predicate类型,将传入的条件和当前的条件以或者的关系过滤数据
default Predicate<T> or(Predicate<? super T> other) {
    Objects.requireNonNull(other);
    return (t) -> test(t) || other.test(t);
}
//negate就是将当前条件取反
default Predicate<T> negate() {
    return (t) -> !test(t);
}
static <T> Predicate<T> isEqual(Object targetRef) {
    return (null == targetRef)
            ? Objects::isNull
            : object -> targetRef.equals(object);
}


看几个案例:


public List<Integer> conditionFilterAnd(List<Integer> list, Predicate<Integer> predicate,Predicate<Integer> predicate2){
    return list.stream().filter(predicate.and(predicate2)).collect(Collectors.toList());
}
public List<Integer> conditionFilterOr(List<Integer> list, Predicate<Integer> predicate,Predicate<Integer> predicate2){
    return list.stream().filter(predicate.or(predicate2)).collect(Collectors.toList());
}
public List<Integer> conditionFilterNegate(List<Integer> list, Predicate<Integer> predicate){
    return list.stream().filter(predicate.negate()).collect(Collectors.toList());
}
//大于5并且是偶数
result = predicateTest.conditionFilterAnd(list, integer -> integer > 5, integer1 -> integer1 % 2 == 0);
result.forEach(System.out::println);//6 8 10
System.out.println("-------");
//大于5或者是偶数
result = predicateTest.conditionFilterOr(list, integer -> integer > 5, integer1 -> integer1 % 2 == 0);
result.forEach(System.out::println);//2 4 6 8 9 10
System.out.println("-------");
//条件取反
result = predicateTest.conditionFilterNegate(list,integer2 -> integer2 > 5);
result.forEach(System.out::println);// 1 2 3 4 5
System.out.println("-------");


最后再来看一下Predicate接口中的唯一一个静态方法(小纵范围使用):


isEqual方法返回类型也是Predicate,也就是说通过isEqual方法得到的也是一个用来进行条件判断的函数式接口实例。而返回的这个函数式接口实例是通过传入的targetRef的equals方法进行判断的。我们看一下具体


public static void main(String[] args) {
        System.out.println(Predicate.isEqual("test").test("test")); //true
        System.out.println(Predicate.isEqual(null).test("test")); //false
        System.out.println(Predicate.isEqual(null).test(null)); //true
        System.out.println(Predicate.isEqual(1).test(new Integer(1))); //true
        //注意 这里是false的
        System.out.println(Predicate.isEqual(new Long(1)).test(new Integer(1))); //false
    }


其他Predicate扩展接口:


BiPredicate:boolean test(T t, U u);接受两个参数的,判断返回bool


DoublePredicate:boolean test(double value);入参为double的谓词函数


IntPredicate:boolean test(int value);入参为int的谓词函数


LongPredicate:boolean test(long value);入参为long的谓词函数


public interface Function


这个接口非常非常总要。是很上层的一个抽象。除了一个抽象方法apply外,其默认实现了3个default方法,分别是compose、andThen和identity。


  default <V> Function<T, V> andThen(Function<? super R, ? extends V> after) {
        Objects.requireNonNull(after);
        return (T t) -> after.apply(apply(t));
    }
 default <V> Function<V, R> compose(Function<? super V, ? extends T> before) {
        Objects.requireNonNull(before);
        return (V v) -> apply(before.apply(v));
    }


compose 和 andThen 的不同之处是函数执行的顺序不同。andThen就是按照正常思维:先执行调用者,再执行入参的。然后compose 是反着来的,这点需要注意。


看看唯一的一个静态方法identity:

static <T> Function<T, T> identity() {
        return t -> t;
    }

我们会发现,identity啥都没做,只是返回了一个Function方法,并且是两个泛型都一样的方法,意义着实不是太大。下面看一个复杂点的例子,各位感受一下:


 public static void main(String[] args) {
        Function<Integer, Integer> times2 = i -> i * 2; //加倍函数
        Function<Integer, Integer> squared = i -> i * i; //平方函数
        System.out.println(times2.apply(4)); //8
        System.out.println(squared.apply(4)); //16
        System.out.println(times2.compose(squared).apply(4));  //32   先4×4然后16×2, 先执行参数,再执行调用者
        System.out.println(times2.andThen(squared).apply(4));  //64   先4×2,然后8×8, 先执行调用者,再执行参数
        //看看这个例子Function.identity()构建出一个恒等式函数而已,方便方法的连缀 这就是它的唯一优点
        System.out.println(Function.identity().compose(squared).apply(4));   //16 先执行4*4,再执行identity 值不变
    }


由Function,可以扩展出高阶函数。如泛型中有个类型还是Function,这种需要还是经常有的,所以BiFunction提供了二元函数的一个接口声明


  public static void main(String[] args) {
        BiFunction<Integer, Integer, Integer> biFunction = (x, y) -> x + y;
        System.out.println(biFunction.apply(4, 5)); //9
        System.out.println(biFunction.andThen(x -> x + 10).apply(4, 5)); //19
    }


二元函数没有compose能力,只是默认实现了andThen。有了一元和二元函数,那么可以通过组合扩展出更多的函数可能。


Function相关扩展接口:


BiFunction :R apply(T t, U u);接受两个参数,返回一个值,代表一个二元函数;


DoubleFunction :R apply(double value);只处理double类型的一元函数;


ToDoubleFunction:double applyAsDouble(T value);返回double的一元函数;


ToDoubleBiFunction:double applyAsDouble(T t, U u);返回double的二元函数;


IntToLongFunction:long applyAsLong(int value);接受int返回long的一元函数;


里面有很多关于int、long、double的一元二元函数,这里就不一一例举了。


Operator


Operator其实就是Function,函数有时候也叫作算子。算子在Java8中接口描述更像是函数的补充,和上面的很多类型映射型函数类似。它包含UnaryOperator和BinaryOperator。分别对应单元算子和二元算子。


UnaryOperator

 @FunctionalInterface
    public interface UnaryOperator<T> extends Function<T, T> {
        static <T> java.util.function.UnaryOperator<T> identity() {
            return t -> t;
        }
    }
  @FunctionalInterface
    public interface BinaryOperator<T> extends BiFunction<T,T,T> {
        public static <T> java.util.function.BinaryOperator<T> minBy(Comparator<? super T> comparator) {
            Objects.requireNonNull(comparator);
            return (a, b) -> comparator.compare(a, b) <= 0 ? a : b;
        }
        public static <T> java.util.function.BinaryOperator<T> maxBy(Comparator<? super T> comparator) {
            Objects.requireNonNull(comparator);
            return (a, b) -> comparator.compare(a, b) >= 0 ? a : b;
        }
    }

很明显,算子就是一个针对同类型输入输出的一个映射。在此接口下,只需声明一个泛型参数T即可。直接上例子,就非常清楚使用场景了:


  public static void main(String[] args) {
        UnaryOperator<Integer> unaryOperator = x -> x + 10;
        BinaryOperator<Integer> binaryOperator = (x, y) -> x + y;
        System.out.println(unaryOperator.apply(10)); //20
        System.out.println(binaryOperator.apply(5, 10)); //15
        //继续看看BinaryOperator提供的两个静态方法   也挺好用的
        BinaryOperator<Integer> min = BinaryOperator.minBy(Integer::compare);
        BinaryOperator<Integer> max = BinaryOperator.maxBy(Integer::compareTo);
        System.out.println(min.apply(10, 20)); //10
        System.out.println(max.apply(10, 20)); //20
    }


BinaryOperator提供了两个默认的static快捷实现,帮助实现二元函数min(x,y)和max(x,y),使用时注意的是排序器可别传反了:)


提示一个小点:compareTo是Integer的实例方法,而compare是静态方法。其实1.8之后,Interger等都提供了min、max、sum等静态方法


其他的Operator接口:(不解释了)


   LongUnaryOperator:long applyAsLong(long operand);


   LongBinaryOperator:long applyAsLong(long left, long right);

    。。。省略不写了


最后


我们会发现,JDK的设计还是很有规律的。每个函数式接口对基本数据类型的中的int、long、double都提供了对应的扩展接口。可我们是否想过?为什么别的数据基本类型没有对应接口呢?这个我在Stream那一章有说明原因,各位看官可跳转到那里观看


相关文章
|
Java 数据处理
|
存储 算法 程序员
C++ 11新特性之function
C++ 11新特性之function
396 9
|
Java 编译器 API
带你了解“Java新特性——模块化”
带你了解“Java新特性——模块化”
530 11
|
机器学习/深度学习
现代深度学习框架构建问题之Sigmoid类实现Function接口如何解决
现代深度学习框架构建问题之Sigmoid类实现Function接口如何解决
120 4
|
算法 Java 编译器
Java基础之lambda表达式(JDK1.8新特性)
Java基础之lambda表达式(JDK1.8新特性)
190 1
|
Java API 数据处理
Java JDK 8新特性详解及应用实例
Java JDK 8新特性详解及应用实例
|
Java API 数据处理
Java 8的新特性详解
Java 8的新特性详解
|
8月前
|
人工智能 Python
083_类_对象_成员方法_method_函数_function_isinstance
本内容主要讲解Python中的数据类型与面向对象基础。回顾了变量类型(如字符串`str`和整型`int`)及其相互转换,探讨了加法在不同类型中的表现。通过超市商品分类比喻,引出“类型”概念,并深入解析类(class)与对象(object)的关系,例如具体橘子是橘子类的实例。还介绍了`isinstance`函数判断类型、`type`与`help`探索类型属性,以及`str`和`int`的不同方法。最终总结类是抽象类型,对象是其实例,不同类型的对象有独特运算和方法,为后续学习埋下伏笔。
184 7
083_类_对象_成员方法_method_函数_function_isinstance
|
8月前
|
Python
[oeasy]python086方法_method_函数_function_区别
本文详细解析了Python中方法(method)与函数(function)的区别。通过回顾列表操作如`append`,以及随机模块的使用,介绍了方法作为类的成员需要通过实例调用的特点。对比内建函数如`print`和`input`,它们无需对象即可直接调用。总结指出方法需基于对象调用且包含`self`参数,而函数独立存在无需`self`。最后提供了学习资源链接,方便进一步探索。
226 17