tft每日頭條

 > 生活

 > jdk8函數

jdk8函數

生活 更新时间:2025-02-12 00:21:41

這段時間閑着沒事,把之前看了一眼但不在意的知識點又回顧了一遍,這種感覺就像有個青梅竹馬的小學女同學,從小認識很久卻沒有認真對待,現在一看感覺是那麼的親切 但 又很陌生。所以,決定好好的認識以下她,你懂這種感覺嗎?

jdk8函數(1.8函數式接口-Predicate)1

  • Predicate<T>:接收T類型對象并返回boolean,用于定義執行條件。
  • Consumer<T>:接收T類型對象,沒有返回值,用于定義執行具體任務。

如果這樣描述,我們不是很好理解,我們需求導向吧。

業務需求:

一個人要親另一個人,但是必須性别不一樣才行。

public class Person { private String name; private String sex; public void kiss(Person person) { if(person.getSex().equals(this.getSex())) { System.out.println("開不了口"); } else { System.out.println("那就不客氣了"); } } public static void main(String[] args) { Person person1 = new Person("老王","男"); Person person2 = new Person("志玲","女"); Person person3 = new Person("老張","男"); person1.kiss(person2); person1.kiss(person3); } public Person(String name, String sex) { this.name = name; this.sex = sex; } }

輸出結果:

那就不客氣了

開不了口

按照以前的思路這樣寫感覺沒有什麼問題,對吧。但是這樣并不是很科學,因為什麼呢,因為人是會變的,萬一有一天他突然想通了,打算從櫃子裡面出來了。出來之後,感覺不是很好,又打算回到櫃子裡面去。

所以我們可以在定義kiss方法的時候,制定一個動态條件(Predicate),以及動态行為(Consumer)。

重構代碼

public void kiss(Person person , Predicate<Person> predicate, Consumer<Person> consumer) { /*未知條件*/ if(predicate.test(person)) { /*開始對應行為*/ consumer.accept(person); } } public static void main(String[] args) { Person person = new Person("老王","男"); Person person2 = new Person("志玲","女"); Person person3 = new Person("老張","男"); person.kiss(person2,p->p.getSex().equals("女"),c->{ System.out.println("那我就不客氣啦!"); }); person.kiss(person2,p->p.getSex().equals("女"),c->{ System.out.println("今天感覺不對,開不了口!"); }); person.kiss(person3,p->p.getSex().equals("男"),c->{ System.out.println("躲在櫃子裡這麼久,憋死老子了!"); }); }

輸出結果:

那我就不客氣啦!

今天感覺不對,開不了口!

躲在櫃子裡這麼久,憋死老子了!

總結:什麼時候用函數式接口呢,在定義行為的時候,你也不太确定有具體什麼行為。隻有當它馬上運行時,根據不同的條件作出不同的行為。這樣子,代碼的靈活性就會非常高。

,

更多精彩资讯请关注tft每日頭條,我们将持续为您更新最新资讯!

查看全部

相关生活资讯推荐

热门生活资讯推荐

网友关注

Copyright 2023-2025 - www.tftnews.com All Rights Reserved