最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

Java Predicate及Consumer接口函數(shù)代碼實現(xiàn)解析

 更新時間:2020年06月08日 11:29:11   作者:笨拙的小菜鳥  
這篇文章主要介紹了Java Predicate及Consumer接口函數(shù)代碼實現(xiàn)解析,文中通過示例代碼介紹的非常詳細,對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友可以參考下

Predicate函數(shù)編程

Predicate功能判斷輸入的對象是否符合某個條件。官方文檔解釋到:Determines if the input object matches some criteria.

了解Predicate接口作用后,在學(xué)習(xí)Predicate函數(shù)編程前,先看一下Java 8關(guān)于Predicate的源碼:

@FunctionalInterface
public interface Predicate<T> {

  /**
   * Evaluates this predicate on the given argument.
   *
   * @param t the input argument
   * @return {@code true} if the input argument matches the predicate,
   * otherwise {@code false}
   */
  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);
  }
}

從上面代碼可以發(fā)現(xiàn),Java 8新增了接口的默認(default)方法和(static)靜態(tài)方法。在Java 8以前,接口里的方法要求全部是抽象方法。但是靜態(tài)(static)方法只能通過接口名調(diào)用,不可以通過實現(xiàn)類的類名或者實現(xiàn)類的對象調(diào)用;默認(default)方法只能通過接口實現(xiàn)類的對象來調(diào)用。

接下來主要來使用接口方法test,可以使用匿名內(nèi)部類提供test()方法的實現(xiàn),也可以使用lambda表達式實現(xiàn)test()。
體驗一下Predicate的函數(shù)式編程,使用lambda實現(xiàn)。其測試代碼如下:

@Test
public void testPredicate(){
  java.util.function.Predicate<Integer> boolValue = x -> x > 5;
  System.out.println(boolValue.test(1));//false
  System.out.println(boolValue.test(6));//true
}

第1行代碼:定義一個Predicate實現(xiàn),入?yún)镮nteger,返回傳入?yún)?shù)與5做比較。
第2,3行代碼調(diào)用第一行,傳入相關(guān)參數(shù)。

Consumer函數(shù)編程

Consumer接口的文檔聲明如下:

An operation which accepts a single input argument and returns no result. Unlike most other functional interfaces, Consumer is expected to operate via side-effects.

即接口表示一個接受單個輸入?yún)?shù)并且沒有返回值的操作。不像其它函數(shù)式接口,Consumer接口期望執(zhí)行帶有副作用的操作(Consumer的操作可能會更改輸入?yún)?shù)的內(nèi)部狀態(tài))。

同樣,在了解Consumer函數(shù)編程前,看一下Consumer源代碼,其源代碼如下:

@FunctionalInterface
public interface Consumer<T> {

  /**
   * Performs this operation on the given argument.
   *
   * @param t the input argument
   */
  void accept(T t);

  /**
   * Returns a composed {@code Consumer} that performs, in sequence, this
   * operation followed by the {@code after} operation. If performing either
   * operation throws an exception, it is relayed to the caller of the
   * composed operation. If performing this operation throws an exception,
   * the {@code after} operation will not be performed.
   *
   * @param after the operation to perform after this operation
   * @return a composed {@code Consumer} that performs in sequence this
   * operation followed by the {@code after} operation
   * @throws NullPointerException if {@code after} is null
   */
  default Consumer<T> andThen(Consumer<? super T> after) {
    Objects.requireNonNull(after);
    return (T t) -> { accept(t); after.accept(t); };
  }
}

從上面代碼可以看出,Consumer使用了Java 8接口新特性——接口默認(default)方法。接下來使用接口方法accept,體驗一下Consumer函數(shù)編程。其測試代碼如下:

@Test
public void testConsumer(){
  User user = new User("zm");
  //接受一個參數(shù)
  Consumer<User> userConsumer = User1 -> User1.setName("zmChange");
  userConsumer.accept(user);
  System.out.println(user.getName());//zmChange
}

在Java 8之前的實現(xiàn)如下:

@Test
public void test(){
  User user = new User("zm");
  this.change(user);
  System.out.println(user.getName());//輸出zmChange
}

private void change(User user){
  user.setName("zmChange");
}

Predicate和Consumer綜合應(yīng)用

為了詳細說明Predicate和Consumer接口,通過一個學(xué)生例子:Student類包含姓名、分數(shù)以及待付費用,每個學(xué)生可根據(jù)分數(shù)獲得不同程度的費用折扣。

Student類源代碼:

public class Student {

  String firstName;

  String lastName;

  Double grade;

  Double feeDiscount = 0.0;
  Double baseFee = 2000.0;
  public Student(String firstName, String lastName, Double grade) {
    this.firstName = firstName;
    this.lastName = lastName;
    this.grade = grade;
  }

  public void printFee(){
    Double newFee = baseFee - ((baseFee * feeDiscount)/100);
    System.out.println("The fee after discount: " + newFee);
  }
}

然后分別聲明一個接受Student對象的Predicate接口以及Consumer接口的實現(xiàn)類。本例子使用Predicate接口實現(xiàn)類的test()方法判斷輸入的Student對象是否擁有費用打折的資格,然后使用Consumer接口的實現(xiàn)類更新輸入的Student對象的折扣。

public class PredicateConsumerDemo {

  public static Student updateStudentFee(Student student, Predicate<Student> predicate, Consumer<Student> consumer){
    if (predicate.test(student)){
      consumer.accept(student);
    }
    return student;
  }

}

Predicate和Consumer接口的test()和accept()方法都接受一個泛型參數(shù)。不同的是test()方法進行某些邏輯判斷并返回一個boolean值,而accept()接受并改變某個對象的內(nèi)部值。updateStudentFee方法的調(diào)用如下所示:

public class Test {
  public static void main(String[] args) {
    Student student1 = new Student("Ashok","Kumar", 9.5);

    student1 = updateStudentFee(student1,
        //Lambda expression for Predicate interface
        student -> student.grade > 8.5,
        //Lambda expression for Consumer inerface
        student -> student.feeDiscount = 30.0);
    student1.printFee(); //The fee after discount: 1400.0

    Student student2 = new Student("Rajat","Verma", 8.0);
    student2 = updateStudentFee(student2,
        //Lambda expression for Predicate interface
        student -> student.grade >= 8,
        //Lambda expression for Consumer inerface
        student -> student.feeDiscount = 20.0);
    student2.printFee();//The fee after discount: 1600.0

  }
}

通過簡單對Predicate接口和Consumer接口進行應(yīng)用,對函數(shù)式編程有了一個直觀認識。

以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。

相關(guān)文章

  • Java使用POI-TL實現(xiàn)生成有個性的簡歷

    Java使用POI-TL實現(xiàn)生成有個性的簡歷

    POI-TL?是一個基于?Apache?POI?的?Java?庫,專注于在?Microsoft?Word?文檔(.docx?格式)中進行模板填充和動態(tài)內(nèi)容生成,下面我們看看如何使用POI-TL生成有個性的簡歷吧
    2024-11-11
  • 如何通過一個注解實現(xiàn)MyBatis字段加解密

    如何通過一個注解實現(xiàn)MyBatis字段加解密

    用戶隱私很重要,因此很多公司開始做數(shù)據(jù)加減密改造,下面這篇文章主要給大家介紹了關(guān)于如何通過一個注解實現(xiàn)MyBatis字段加解密的相關(guān)資料,需要的朋友可以參考下
    2022-02-02
  • SpringMVC項目異常處理機制詳解

    SpringMVC項目異常處理機制詳解

    SpringMVC是一種基于Java,實現(xiàn)了Web MVC設(shè)計模式,請求驅(qū)動類型的輕量級Web框架,即使用了MVC架構(gòu)模式的思想,將Web層進行職責(zé)解耦?;谡埱篁?qū)動指的就是使用請求-響應(yīng)模型,框架的目的就是幫助我們簡化開發(fā),SpringMVC也是要簡化我們?nèi)粘eb開發(fā)
    2022-08-08
  • Maven基礎(chǔ)知識大梳理

    Maven基礎(chǔ)知識大梳理

    這篇文章主要是Maven基礎(chǔ)知識大梳理,Maven主要是用來解決導(dǎo)入java類依賴的jar,編譯java項目主要問題,大家可以讀一讀這篇文章,更深一步的了解Maven
    2021-08-08
  • Spring Security實現(xiàn)自動登陸功能示例

    Spring Security實現(xiàn)自動登陸功能示例

    自動登錄在很多網(wǎng)站和APP上都能用的到,解決了用戶每次輸入賬號密碼的麻煩。本文就使用Spring Security實現(xiàn)自動登陸功能,具有一定的參考價值,感興趣的小伙伴們可以參考一下
    2021-11-11
  • 詳解MyBatis中column屬性的總結(jié)

    詳解MyBatis中column屬性的總結(jié)

    在MyBatis的映射中有column這么一個屬性,我一直以為它映射的是數(shù)據(jù)庫表中的列名,但經(jīng)過學(xué)習(xí)發(fā)現(xiàn)他似乎映射的是SQL語句中的列名,或者說是查詢結(jié)果所得到的表的列名,這篇文章主要介紹了MyBatis中column屬性的總結(jié),需要的朋友可以參考下
    2022-09-09
  • HashMap每次擴容為什么是2倍

    HashMap每次擴容為什么是2倍

    當HashMap在初始化沒有指定容量的情況下,首次添加元素時,數(shù)組的容量為16;當超出閾值,數(shù)組容量為擴容為之前的2倍,為什么HashMap每次擴容都是之前的2倍?下面就介紹一下
    2024-11-11
  • MyBatis實現(xiàn)簡單的數(shù)據(jù)表分月存儲

    MyBatis實現(xiàn)簡單的數(shù)據(jù)表分月存儲

    本文主要介紹了MyBatis實現(xiàn)簡單的數(shù)據(jù)表分月存儲,文中通過示例代碼介紹的非常詳細,對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧
    2023-03-03
  • Maven項目中讀取src/main/resources目錄下的配置文件的方法

    Maven項目中讀取src/main/resources目錄下的配置文件的方法

    本篇文章主要介紹了Maven項目中讀取src/main/resources目錄下的配置文件的方法,小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧
    2017-12-12
  • java?緩沖流的概念使用方法以及實例詳解

    java?緩沖流的概念使用方法以及實例詳解

    這篇文章主要為大家介紹了java?緩沖流的概念使用方法以及實例詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪
    2023-06-06

最新評論

博湖县| 万山特区| 突泉县| 白城市| 东安县| 老河口市| 安义县| 晴隆县| 恩施市| 沂南县| 徐汇区| 刚察县| 普宁市| 五常市| 石嘴山市| 新化县| 微山县| 卢龙县| 澄迈县| 阿拉善左旗| 东源县| 阳信县| 石楼县| 定陶县| 湘潭县| 疏附县| 三明市| 腾冲县| 搜索| 长岛县| 察雅县| 本溪市| 湘乡市| 曲阜市| 丹江口市| 新丰县| 青海省| 故城县| 天长市| 泉州市| 襄城县|