自拍偷在线精品自拍偷,亚洲欧美中文日韩v在线观看不卡

玩轉(zhuǎn)Java8的Stream之函數(shù)式接口

開發(fā) 后端
Java8Stream 作為函數(shù)式編程的一種具體實現(xiàn),開發(fā)者無需關(guān)注怎么做,只需知道要做什么,各種操作符配合簡潔明了的函數(shù)式接口給開發(fā)者帶來了簡單快速處理數(shù)據(jù)的體驗。

[[327517]]

函數(shù)式接口是伴隨著Stream的誕生而出現(xiàn)的,Java8Stream 作為函數(shù)式編程的一種具體實現(xiàn),開發(fā)者無需關(guān)注怎么做,只需知道要做什么,各種操作符配合簡潔明了的函數(shù)式接口給開發(fā)者帶來了簡單快速處理數(shù)據(jù)的體驗。

函數(shù)式接口

什么是函數(shù)式接口?簡單來說就是只有一個抽象函數(shù)的接口。為了使得函數(shù)式接口的定義更加規(guī)范,java8 提供了@FunctionalInterface 注解告訴編譯器在編譯器去檢查函數(shù)式接口的合法性,以便在編譯器在編譯出錯時給出提示。為了更加規(guī)范定義函數(shù)接口,給出如下函數(shù)式接口定義規(guī)則:

  •  有且僅有一個抽象函數(shù)
  •  必須要有@FunctionalInterface 注解
  •  可以有默認方法

可以看出函數(shù)式接口的編寫定義非常簡單,不知道大家有沒有注意到,其實我們經(jīng)常會用到函數(shù)式接口,如Runnable 接口,它就是一個函數(shù)式接口: 

  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();  

過去我們會使用匿名內(nèi)部類來實現(xiàn)線程的執(zhí)行體:

 

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

現(xiàn)在我們使用Lambda 表達式,這里函數(shù)式接口的使用沒有體現(xiàn)函數(shù)式編程思想,這里輸出字符到標準輸出流中,產(chǎn)生了副作用,起到了簡化代碼的作用,當然還有裝B。 

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

Java8 util.function 包下自帶了43個函數(shù)式接口,大體分為以下幾類:

  •  Consumer 消費接口
  •  Function 功能接口
  •  Operator 操作接口
  •  Predicate 斷言接口
  •  Supplier 生產(chǎn)接口

其他接口都是在此基礎(chǔ)上變形定制化罷了。

函數(shù)式接口詳細介紹

這里只介紹最基礎(chǔ)的函數(shù)式接口,至于它的變體只要明白了基礎(chǔ)自然就能夠明白。前篇:玩轉(zhuǎn)Java8中的 Stream 之從零認識 Stream

Consumer

消費者接口,就是用來消費數(shù)據(jù)的。 

  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接受一個變量,也就是說你在使用這個函數(shù)式接口的時候,給你提供了數(shù)據(jù),你只要接收使用就可以了;andThen 是一個默認方法,接受一個Consumer 類型,當你對一個數(shù)據(jù)使用一次還不夠爽的時候,你還能再使用一次,當然你其實可以爽無數(shù)次,只要一直使用andThan方法。

Function

何為Function呢?比如電視機,給你帶來精神上的愉悅,但是它需要用電啊,電視它把電轉(zhuǎn)換成了你荷爾蒙,這就是Function,簡單電說,F(xiàn)unction 提供一種轉(zhuǎn)換功能。 

  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 函數(shù),apply 接受T類型數(shù)據(jù)并返回R類型數(shù)據(jù),就是將T類型的數(shù)據(jù)轉(zhuǎn)換成R類型的數(shù)據(jù),它還提供了compose、andThen、identity 三個默認方法,compose 接受一個Function,andThen也同樣接受一個Function,這里的andThen 與Consumer 的andThen 類似,在apply之后在apply一遍,compose 則與之相反,在apply之前先apply(這兩個apply具體處理內(nèi)容一般是不同的),identity 起到了類似海關(guān)的作用,外國人想要運貨進來,總得交點稅吧,然后貨物才能安全進入中國市場,當然了想不想收稅還是你說了算的:。

Operator

可以簡單理解成算術(shù)中的各種運算操作,當然不僅僅是運算這么簡單,因為它只定義了運算這個定義,但至于運算成什么樣你說了算。由于沒有最基礎(chǔ)的Operator,這里將通過 BinaryOperator、IntBinaryOperator來理解Operator 函數(shù)式接口,先從簡單的IntBinaryOperator開始。

IntBinaryOperator

從名字可以知道,這是一個二元操作,并且是Int 類型的二元操作,那么這個接口可以做什么呢,除了加減乘除,還可以可以實現(xiàn)平方(兩個相同int 數(shù)操作起來不就是平方嗎),還是先看看它的定義吧: 

  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 接口內(nèi)只有一個applyAsInt 方法,其接收兩個int 類型的參數(shù),并返回一個int 類型的結(jié)果,其實這個跟Function 接口的apply 有點像,但是這里限定了,只能是int類型。

BinaryOperator

BinaryOperator 二元操作,看起來它和IntBinaryOperator 是父子關(guān)系,實際上這兩者沒有半點關(guān)系,但他們在功能上還是有相似之處的: 

  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默認方法,并且參數(shù)都是Comparator,就是根據(jù)傳入的比較器的比較規(guī)則找出最小最大的數(shù)據(jù)。

Predicate

斷言、判斷,對輸入的數(shù)據(jù)根據(jù)某種標準進行評判,最終返回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類型的數(shù)據(jù),返回 boolean 類型,即對數(shù)據(jù)進行某種規(guī)則的評判,如果符合則返回true,否則返回false;Predicate接口還提供了 and、negate、or,與 取反 或等,isEqual 判斷兩個參數(shù)是否相等等默認函數(shù)。

Supplier

生產(chǎn)、提供數(shù)據(jù): 

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

非常easy,get方法返回一個T類數(shù)據(jù),可以提供重復(fù)的數(shù)據(jù),或者隨機種子都可以,就這么簡單。

函數(shù)式接口實戰(zhàn)

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.     }  

這里使用標準輸出,還是產(chǎn)生了副作用,但是這種程度是可以允許的

Function

1.轉(zhuǎn)換,將字符串轉(zhuǎn)成長度 

  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.     }  

結(jié)果如圖:

Operator

1.BinaryOperator

這里實現(xiàn)找最大值: 

  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

這里實現(xiàn)累加功能: 

  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最小的兩個數(shù) 

  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的數(shù)  
  5.                 .sorted() //自然順序排序  
  6.                 .limit(2) //取前兩個  
  7.                 .forEach(System.out::println);  
  8.     }  

Supplier

這里一直生產(chǎn)2這個數(shù)字,為了能停下來,使用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.     }  

如圖:

總結(jié)

Java8的Stream 基本上都是使用util.function包下的函數(shù)式接口來實現(xiàn)函數(shù)式編程的,而函數(shù)式接口也就只分為 Function、Operator、Consumer、Predicate、Supplier 這五大類,只要能理解掌握最基礎(chǔ)的五大類用法,其他變種也能觸類旁通。 

 

責(zé)任編輯:龐桂玉 來源: Java知音
相關(guān)推薦

2023-07-26 07:13:55

函數(shù)接口Java 8

2023-03-15 17:37:26

Java8ListMap

2022-12-26 07:47:37

JDK8函數(shù)式接口

2020-10-16 10:07:03

Lambda表達式Java8

2015-09-30 09:34:09

java8字母序列

2023-05-12 07:40:01

Java8API工具

2014-04-15 09:40:04

Java8stream

2014-07-16 16:42:41

Java8streamreduce

2020-09-24 10:57:12

編程函數(shù)式前端

2024-02-28 08:37:28

Lambda表達式Java函數(shù)式接口

2020-09-22 11:00:11

Java技術(shù)開發(fā)

2021-08-03 07:51:43

Java 8 函數(shù)接口

2024-03-08 09:45:21

Lambda表達式Stream

2024-10-09 08:42:03

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代碼

2024-08-19 02:00:00

FunctionJava8接口

2019-08-05 08:05:27

Java開發(fā)代碼
點贊
收藏

51CTO技術(shù)棧公眾號