玩转Java8的Stream之函数式接口

开发 后端
Java8Stream 作为函数式编程的一种具体实现,开发者无需关注怎么做,只需知道要做什么,各种操作符配合简洁明了的函数式接口给开发者带来了简单快速处理数据的体验。

[[327517]]

函数式接口是伴随着Stream的诞生而出现的,Java8Stream 作为函数式编程的一种具体实现,开发者无需关注怎么做,只需知道要做什么,各种操作符配合简洁明了的函数式接口给开发者带来了简单快速处理数据的体验。

函数式接口

什么是函数式接口?简单来说就是只有一个抽象函数的接口。为了使得函数式接口的定义更加规范,java8 提供了@FunctionalInterface 注解告诉编译器在编译器去检查函数式接口的合法性,以便在编译器在编译出错时给出提示。为了更加规范定义函数接口,给出如下函数式接口定义规则:

  •  有且仅有一个抽象函数
  •  必须要有@FunctionalInterface 注解
  •  可以有默认方法

可以看出函数式接口的编写定义非常简单,不知道大家有没有注意到,其实我们经常会用到函数式接口,如Runnable 接口,它就是一个函数式接口: 

  1. @FunctionalInterface  
  2. public interface Runnable {  
  3.     /**  
  4.      * When an object implementing interface <code>Runnable</code> is used  
  5.      * to create a thread, starting the thread causes the object's  
  6.      * <code>run</code> method to be called in that separately executing  
  7.      * thread.  
  8.      * <p>  
  9.      * The general contract of the method <code>run</code> is that it may  
  10.      * take any action whatsoever.  
  11.      *  
  12.      * @see     java.lang.Thread#run()  
  13.      */  
  14.     public abstract void run();  

过去我们会使用匿名内部类来实现线程的执行体:

 

  1. new Thread(new Runnable() {  
  2.             @Override  
  3.             public void run() {  
  4.                 System.out.println("Hello FunctionalInterface");  
  5.             }  
  6.         }).start();  

现在我们使用Lambda 表达式,这里函数式接口的使用没有体现函数式编程思想,这里输出字符到标准输出流中,产生了副作用,起到了简化代码的作用,当然还有装B。 

  1. new Thread(()-> 
  2.            System.out.println("Hello FunctionalInterface");  
  3.        }).start(); 

Java8 util.function 包下自带了43个函数式接口,大体分为以下几类:

  •  Consumer 消费接口
  •  Function 功能接口
  •  Operator 操作接口
  •  Predicate 断言接口
  •  Supplier 生产接口

其他接口都是在此基础上变形定制化罢了。

函数式接口详细介绍

这里只介绍最基础的函数式接口,至于它的变体只要明白了基础自然就能够明白。前篇:玩转Java8中的 Stream 之从零认识 Stream

Consumer

消费者接口,就是用来消费数据的。 

  1. @FunctionalInterface  
  2. public interface Consumer<T> {  
  3.     /**  
  4.      * Performs this operation on the given argument.  
  5.      *  
  6.      * @param t the input argument  
  7.      */  
  8.     void accept(T t);  
  9.     /** 
  10.       * Returns a composed {@code Consumer} that performs, in sequence, this  
  11.      * operation followed by the {@code after} operation. If performing either  
  12.      * operation throws an exception, it is relayed to the caller of the  
  13.      * composed operation.  If performing this operation throws an exception,  
  14.      * the {@code after} operation will not be performed.  
  15.      *  
  16.      * @param after the operation to perform after this operation  
  17.      * @return a composed {@code Consumer} that performs in sequence this  
  18.      * operation followed by the {@code after} operation  
  19.      * @throws NullPointerException if {@code after} is null  
  20.      */  
  21.     default Consumer<T> andThen(Consumer<? super T> after) {  
  22.         Objects.requireNonNull(after);  
  23.         return (T t) -> { accept(t); after.accept(t); };  
  24.     }  

Consumer 接口中有accept 抽象方法,accept接受一个变量,也就是说你在使用这个函数式接口的时候,给你提供了数据,你只要接收使用就可以了;andThen 是一个默认方法,接受一个Consumer 类型,当你对一个数据使用一次还不够爽的时候,你还能再使用一次,当然你其实可以爽无数次,只要一直使用andThan方法。

Function

何为Function呢?比如电视机,给你带来精神上的愉悦,但是它需要用电啊,电视它把电转换成了你荷尔蒙,这就是Function,简单电说,Function 提供一种转换功能。 

  1. @FunctionalInterface  
  2. public interface Function<T, R> {  
  3.     /**  
  4.      * Applies this function to the given argument.  
  5.      * 
  6.       * @param t the function argument  
  7.      * @return the function result  
  8.      */  
  9.     R apply(T t);  
  10.     /**  
  11.      * Returns a composed function that first applies the {@code before}  
  12.      * function to its input, and then applies this function to the result.  
  13.      * If evaluation of either function throws an exception, it is relayed to  
  14.      * the caller of the composed function.  
  15.      *  
  16.      * @param <V> the type of input to the {@code before} function, and to the  
  17.      *           composed function  
  18.      * @param before the function to apply before this function is applied  
  19.      * @return a composed function that first applies the {@code before}  
  20.      * function and then applies this function  
  21.      * @throws NullPointerException if before is null  
  22.      *  
  23.      * @see #andThen(Function)  
  24.      */  
  25.     default <V> Function<V, R> compose(Function<? super V, ? extends T> before) {  
  26.         Objects.requireNonNull(before);  
  27.         return (V v) -> apply(before.apply(v));  
  28.     }  
  29.     /**  
  30.      * Returns a composed function that first applies this function to  
  31.      * its input, and then applies the {@code after} function to the result.  
  32.      * If evaluation of either function throws an exception, it is relayed to  
  33.      * the caller of the composed function.  
  34.      *  
  35.      * @param <V> the type of output of the {@code after} function, and of the  
  36.      *           composed function  
  37.      * @param after the function to apply after this function is applied  
  38.      * @return a composed function that first applies this function and then  
  39.      * applies the {@code after} function  
  40.      * @throws NullPointerException if after is null  
  41.      *  
  42.      * @see #compose(Function)  
  43.      */  
  44.     default <V> Function<T, V> andThen(Function<? super R, ? extends V> after) {  
  45.         Objects.requireNonNull(after);  
  46.         return (T t) -> after.apply(apply(t));  
  47.     }  
  48.     /**  
  49.      * Returns a function that always returns its input argument.  
  50.      *  
  51.      * @param <T> the type of the input and output objects to the function  
  52.      * @return a function that always returns its input argument  
  53.      */  
  54.     static <T> Function<T, T> identity() {  
  55.         return t -> t;  
  56.     }  

Function 接口 最主要的就是apply 函数,apply 接受T类型数据并返回R类型数据,就是将T类型的数据转换成R类型的数据,它还提供了compose、andThen、identity 三个默认方法,compose 接受一个Function,andThen也同样接受一个Function,这里的andThen 与Consumer 的andThen 类似,在apply之后在apply一遍,compose 则与之相反,在apply之前先apply(这两个apply具体处理内容一般是不同的),identity 起到了类似海关的作用,外国人想要运货进来,总得交点税吧,然后货物才能安全进入中国市场,当然了想不想收税还是你说了算的:。

Operator

可以简单理解成算术中的各种运算操作,当然不仅仅是运算这么简单,因为它只定义了运算这个定义,但至于运算成什么样你说了算。由于没有最基础的Operator,这里将通过 BinaryOperator、IntBinaryOperator来理解Operator 函数式接口,先从简单的IntBinaryOperator开始。

IntBinaryOperator

从名字可以知道,这是一个二元操作,并且是Int 类型的二元操作,那么这个接口可以做什么呢,除了加减乘除,还可以可以实现平方(两个相同int 数操作起来不就是平方吗),还是先看看它的定义吧: 

  1. @FunctionalInterface  
  2. public interface IntBinaryOperator {  
  3.     /**  
  4.      * Applies this operator to the given operands. 
  5.      *  
  6.      * @param left the first operand 
  7.      * @param right the second operand  
  8.      * @return the operator result  
  9.      */  
  10.     int applyAsInt(int left, int right);  

IntBinaryOperator 接口内只有一个applyAsInt 方法,其接收两个int 类型的参数,并返回一个int 类型的结果,其实这个跟Function 接口的apply 有点像,但是这里限定了,只能是int类型。

BinaryOperator

BinaryOperator 二元操作,看起来它和IntBinaryOperator 是父子关系,实际上这两者没有半点关系,但他们在功能上还是有相似之处的: 

  1. @FunctionalInterface  
  2. public interface BinaryOperator<T> extends BiFunction<T,T,T> {  
  3.     /**  
  4.      * Returns a {@link BinaryOperator} which returns the lesser of two elements  
  5.      * according to the specified {@code Comparator}. 
  6.      *  
  7.      * @param <T> the type of the input arguments of the comparator  
  8.      * @param comparator a {@code Comparator} for comparing the two values  
  9.      * @return a {@code BinaryOperator} which returns the lesser of its operands,  
  10.      *         according to the supplied {@code Comparator}  
  11.      * @throws NullPointerException if the argument is null  
  12.      */  
  13.     public static <T> BinaryOperator<T> minBy(Comparator<? super T> comparator) {  
  14.         Objects.requireNonNull(comparator);  
  15.         return (a, b) -> comparator.compare(a, b) <= 0 ? a : b;  
  16.     }  
  17.     /**  
  18.      * Returns a {@link BinaryOperator} which returns the greater of two elements  
  19.      * according to the specified {@code Comparator}.  
  20.      *  
  21.      * @param <T> the type of the input arguments of the comparator  
  22.      * @param comparator a {@code Comparator} for comparing the two values  
  23.      * @return a {@code BinaryOperator} which returns the greater of its operands,  
  24.      *         according to the supplied {@code Comparator}  
  25.      * @throws NullPointerException if the argument is null  
  26.      */  
  27.     public static <T> BinaryOperator<T> maxBy(Comparator<? super T> comparator) {  
  28.         Objects.requireNonNull(comparator);  
  29.         return (a, b) -> comparator.compare(a, b) >= 0 ? a : b;  
  30.     }  

BinaryOperator 是 BiFunction 生的,而IntBinaryOperator 是从石头里蹦出来的,BinaryOperator 自身定义了minBy、maxBy默认方法,并且参数都是Comparator,就是根据传入的比较器的比较规则找出最小最大的数据。

Predicate

断言、判断,对输入的数据根据某种标准进行评判,最终返回boolean值: 

  1. @FunctionalInterface  
  2. public interface Predicate<T> {  
  3.     /**  
  4.      * Evaluates this predicate on the given argument.  
  5.      * 
  6.      * @param t the input argument  
  7.      * @return {@code true} if the input argument matches the predicate,  
  8.      * otherwise {@code false}  
  9.      */  
  10.     boolean test(T t);  
  11.     /**  
  12.      * Returns a composed predicate that represents a short-circuiting logical  
  13.      * AND of this predicate and another.  When evaluating the composed  
  14.      * predicate, if this predicate is {@code false}, then the {@code other}  
  15.      * predicate is not evaluated.  
  16.      *  
  17.      * <p>Any exceptions thrown during evaluation of either predicate are relayed  
  18.      * to the caller; if evaluation of this predicate throws an exception, the  
  19.      * {@code other} predicate will not be evaluated.  
  20.      *  
  21.      * @param other a predicate that will be logically-ANDed with this  
  22.      *              predicate  
  23.      * @return a composed predicate that represents the short-circuiting logical  
  24.      * AND of this predicate and the {@code other} predicate  
  25.      * @throws NullPointerException if other is null  
  26.      */  
  27.     default Predicate<T> and(Predicate<? super T> other) {  
  28.         Objects.requireNonNull(other);  
  29.         return (t) -> test(t) && other.test(t);  
  30.     }  
  31.     /**  
  32.      * Returns a predicate that represents the logical negation of this  
  33.      * predicate.  
  34.      *  
  35.      * @return a predicate that represents the logical negation of this  
  36.      * predicate  
  37.      */  
  38.     default Predicate<T> negate() {  
  39.         return (t) -> !test(t);  
  40.     }  
  41.     /**  
  42.      * Returns a composed predicate that represents a short-circuiting logical  
  43.      * OR of this predicate and another.  When evaluating the composed  
  44.      * predicate, if this predicate is {@code true}, then the {@code other}  
  45.      * predicate is not evaluated.  
  46.      *  
  47.      * <p>Any exceptions thrown during evaluation of either predicate are relayed  
  48.      * to the caller; if evaluation of this predicate throws an exception, the  
  49.      * {@code other} predicate will not be evaluated.  
  50.      *  
  51.      * @param other a predicate that will be logically-ORed with this  
  52.      *              predicate  
  53.      * @return a composed predicate that represents the short-circuiting logical  
  54.      * OR of this predicate and the {@code other} predicate  
  55.      * @throws NullPointerException if other is null  
  56.      */  
  57.     default Predicate<T> or(Predicate<? super T> other) {  
  58.         Objects.requireNonNull(other);  
  59.         return (t) -> test(t) || other.test(t);  
  60.     }  
  61.     /**  
  62.      * Returns a predicate that tests if two arguments are equal according  
  63.      * to {@link Objects#equals(Object, Object)}.  
  64.      *  
  65.      * @param <T> the type of arguments to the predicate  
  66.      * @param targetRef the object reference with which to compare for equality,  
  67.      *               which may be {@code null}  
  68.      * @return a predicate that tests if two arguments are equal according  
  69.      * to {@link Objects#equals(Object, Object)}  
  70.      */  
  71.     static <T> Predicate<T> isEqual(Object targetRef) {  
  72.         return (null == targetRef)  
  73.                 ? Objects::isNull  
  74.                 : object -> targetRef.equals(object);  
  75.     }  

Predicate的test 接收T类型的数据,返回 boolean 类型,即对数据进行某种规则的评判,如果符合则返回true,否则返回false;Predicate接口还提供了 and、negate、or,与 取反 或等,isEqual 判断两个参数是否相等等默认函数。

Supplier

生产、提供数据: 

  1. @FunctionalInterface  
  2. public interface Supplier<T> {  
  3.     /**  
  4.      * Gets a result.  
  5.      *  
  6.      * @return a result  
  7.      */  
  8.     T get();  

非常easy,get方法返回一个T类数据,可以提供重复的数据,或者随机种子都可以,就这么简单。

函数式接口实战

Consumer

Consumer 用的太多了,不想说太多,如下: 

  1. public class Main {  
  2.     public static void main(String[] args) {  
  3.       Stream.of(1,2,3,4,5,6) 
  4.                  .forEach(integer -> System.out.println(integer)); //输出1,2,3,4,5,6  
  5.     }  

这里使用标准输出,还是产生了副作用,但是这种程度是可以允许的

Function

1.转换,将字符串转成长度 

  1. public class Main {  
  2.     public static void main(String[] args) {  
  3.        Stream.of("hello","FunctionalInterface")  
  4.                 .map(e->e.length())  
  5.                 .forEach(System.out::println);  
  6.     }  

2.运算 

  1. public class FunctionTest {  
  2.     public static void main(String[] args) {  
  3.          public static void main(String[] args) {  
  4.         Function<Integer, Integer> square = integer -> integer * integer; //定义平方运算  
  5.         List<Integer> list = new ArrayList<>();  
  6.         list.add(1);  
  7.         list.add(2);  
  8.         list.add(3);  
  9.         list.add(4); 
  10.         list.stream()  
  11.                 .map(square.andThen(square)) //四次方  
  12.                 .forEach(System.out::println); 
  13.         System.out.println("------");  
  14.         list.stream()  
  15.                 .map(square.compose(e -> e - 1)) //减一再平方  
  16.                 .forEach(System.out::println);  
  17.         System.out.println("------");  
  18.         list.stream().map(square.andThen(square.compose(e->e/2))) //先平方然后除2再平方  
  19.                 .forEach(System.out::println);  
  20.     }  

结果如图:

Operator

1.BinaryOperator

这里实现找最大值: 

  1. public class BinaryOperatorTest {  
  2.     public static void main(String[] args) {  
  3.         Stream.of(2,4,5,6,7,1) 
  4.                  .reduce(BinaryOperator.maxBy(Comparator.comparingInt(Integer::intValue))).ifPresent(System.out::println);  
  5.     }  

Comparator 后期会讲到

2.IntOperator

这里实现累加功能: 

  1. public class BinaryOperatorTest {  
  2.     public static void main(String[] args) {  
  3.         IntBinaryOperator intBinaryOperator = (e1, e2)->e1+e2; //定义求和二元操作  
  4.         IntStream.of(2,4,5,6,7,1) 
  5.                  .reduce(intBinaryOperator).ifPresent(System.out::println); 
  6.      }  

Predicate

筛选出大于0最小的两个数 

  1. public class Main {  
  2.     public static void main(String[] args) {  
  3.         IntStream.of(200,45,89,10,-200,78,94)  
  4.                 .filter(e->e>0) //过滤小于0的数  
  5.                 .sorted() //自然顺序排序  
  6.                 .limit(2) //取前两个  
  7.                 .forEach(System.out::println);  
  8.     }  

Supplier

这里一直生产2这个数字,为了能停下来,使用limit 

  1. public class Main {  
  2.     public static void main(String[] args) {  
  3.         Stream.generate(()->2)  
  4.                 .limit(10)  
  5.                 .forEach(System.out::println);  
  6.     }  

如图:

总结

Java8的Stream 基本上都是使用util.function包下的函数式接口来实现函数式编程的,而函数式接口也就只分为 Function、Operator、Consumer、Predicate、Supplier 这五大类,只要能理解掌握最基础的五大类用法,其他变种也能触类旁通。 

 

责任编辑:庞桂玉 来源: Java知音
相关推荐

2023-07-26 07:13:55

函数接口Java 8

2023-03-15 17:37:26

Java8ListMap

2022-12-26 07:47:37

JDK8函数式接口

2023-05-12 07:40:01

Java8API工具

2020-10-16 10:07:03

Lambda表达式Java8

2015-09-30 09:34:09

java8字母序列

2014-04-15 09:40:04

Java8stream

2014-07-16 16:42:41

Java8streamreduce

2024-02-28 08:37:28

Lambda表达式Java函数式接口

2020-09-24 10:57:12

编程函数式前端

2021-08-03 07:51:43

Java 8 函数接口

2020-09-22 11:00:11

Java技术开发

2024-03-08 09:45:21

Lambda表达式Stream

2022-12-09 07:48:10

Java8Stream表达式

2022-12-30 09:24:23

Java8Stream操作

2022-04-14 15:12:40

Java8Stream列表

2021-02-18 16:06:43

JavaStream代码

2019-08-05 08:05:27

Java开发代码

2020-07-24 08:11:04

Java8ava5语言

2022-01-06 07:39:17

Java Default关键字 Java 基础
点赞
收藏

51CTO技术栈公众号