java 謂詞_java8-謂詞(predicate)

傳遞代碼

我們首先看一個例子,假設你有一個 Apple 類,它有一個getColor方法,還有一個變量inventory保存著一個Apples的列表。你可能想要選出所有的綠蘋果,并返回一個列表。通常我們用篩選(filter)一詞來表達這個概念。在 Java 8之前,你可能會寫這樣一個方法 filterGreenApples :

public static List filterGreenApples(List inventory){

List result = new ArrayList<>();

for (Apple apple: inventory){

if ("green".equals(apple.getColor())) {

result.add(apple);

}

}

return result;

}

但是接下來,有人可能想要選出重的蘋果,比如超過150克,于是你心情沉重地寫了下面這

個方法,甚至用了復制粘貼:

public static List filterHeavyApples(List inventory){

List result = new ArrayList<>();

for (Apple apple: inventory){

if (apple.getWeight() > 150) {

result.add(apple);

}

}

return result;

}

我們都知道軟件工程中復制粘貼的危險——給一個做了更新和修正,卻忘了另一個。嘿,這

兩個方法只有一行不同: if 里面高亮的那行條件。如果這兩個高亮的方法之間的差異僅僅是接受

的重量范圍不同,那么你只要把接受的重量上下限作為參數傳遞給 filter 就行了,比如指定

(150, 1000) 來選出重的蘋果(超過150克),或者指定 (0, 80) 來選出輕的蘋果(低于80克)。

但是,我們前面提過了,Java 8會把條件代碼作為參數傳遞進去,這樣可以避免 filter 方法

出現重復的代碼。現在你可以寫:

public static boolean isGreenApple(Apple apple) {

return "green".equals(apple.getColor());

}

public static boolean isHeavyApple(Apple apple) {

return apple.getWeight() > 150;

}

static List filterApples(List inventory, Predicate p) {

List result = new ArrayList<>();

for (Apple apple: inventory){

if (p.test(apple)) {

result.add(apple);

}

}

return result;

}

要用它的話,你可以寫:

filterApples(inventory, Apple::isGreenApple);

或者

filterApples(inventory, Apple::isHeavyApple);

什么是謂詞?

前面的代碼傳遞了方法 Apple::isGreenApple (它接受參數 Apple 并返回一個

boolean )給 filterApples ,后者則希望接受一個 Predicate 參數。詞 謂詞(predicate)

在數學上常常用來代表一個類似函數的東西,它接受一個參數值,并返回 true 或 false 。你

在后面會看到,Java 8也會允許你寫 Function ——在學校學過函數卻沒學

過謂詞的讀者對此可能更熟悉,但用 Predicate 是更標準的方式,效率也會更高一

點兒,這避免了把 boolean 封裝在 Boolean 里面。

從傳遞方法到 Lambda

把方法作為值來傳遞顯然很有用,但要是為類似于 isHeavyApple 和 isGreenApple 這種可

能只用一兩次的短方法寫一堆定義有點兒煩人。不過Java 8也解決了這個問題,它引入了一套新

記法(匿名函數或Lambda),讓你可以寫

filterApples(inventory, (Apple a) -> "green".equals(a.getColor()) );

或者

filterApples(inventory, (Apple a) -> a.getWeight() > 150 );

甚至

filterApples(inventory, (Apple a) -> a.getWeight() < 80 ||

"brown".equals(a.getColor()) );

完整的代碼為:

public class FilteringApples1 {

public static void main(String[] args) {

List inventory = Arrays.asList(new FilteringApples1.Apple(80, "green"),

new FilteringApples1.Apple(155, "green"),

new FilteringApples1.Apple(120, "red"));

List greenApples2 = filterApples(inventory, (FilteringApples1.Apple a) -> "green".equals(a.getColor()));

System.out.println(greenApples2);

// [Apple{color='green', weight=155}]

List heavyApples2 = filterApples(inventory, (FilteringApples1.Apple a) -> a.getWeight() > 150);

System.out.println(heavyApples2);

// []

List weirdApples = filterApples(inventory, (FilteringApples1.Apple a) -> a.getWeight() < 80 ||

"brown".equals(a.getColor()));

System.out.println(weirdApples);

}

public static List filterApples(List inventory, Predicate p) {

List result = new ArrayList<>();

for (FilteringApples1.Apple apple : inventory) {

if (p.test(apple)) {

result.add(apple);

}

}

return result;

}

public static class Apple {

private int weight = 0;

private String color = "";

public Apple(int weight, String color) {

this.weight = weight;

this.color = color;

}

public Integer getWeight() {

return weight;

}

public void setWeight(Integer weight) {

this.weight = weight;

}

public String getColor() {

return color;

}

public void setColor(String color) {

this.color = color;

}

public String toString() {

return "Apple{" +

"color='" + color + '\'' +

", weight=" + weight +

'}';

}

}

}

java8中內置filter函數

static Collection filter(Collection c, Predicate p);

這樣你甚至都不需要寫 filterApples 了,因為比如先前的調用

filterApples(inventory, (Apple a) -> a.getWeight() > 150 );

就可以直接調用庫方法 filter :

filter(inventory, (Apple a) -> a.getWeight() > 150 );

本文來自互聯網用戶投稿,該文觀點僅代表作者本人,不代表本站立場。本站僅提供信息存儲空間服務,不擁有所有權,不承擔相關法律責任。
如若轉載,請注明出處:http://www.pswp.cn/news/541928.shtml
繁體地址,請注明出處:http://hk.pswp.cn/news/541928.shtml
英文地址,請注明出處:http://en.pswp.cn/news/541928.shtml

如若內容造成侵權/違法違規/事實不符,請聯系多彩編程網進行投訴反饋email:809451989@qq.com,一經查實,立即刪除!

相關文章

getlong_Java LocalDateTime類| 帶示例的getLong()方法

getlongLocalDateTime類的getLong()方法 (LocalDateTime Class getLong() method) getLong() method is available in java.time package. getLong()方法在java.time包中可用。 getLong() method is used to get the value as long for the given temporal field from this dat…

java.io和util的區別_Java NIO與IO的區別和比較

Java NIO與IO的區別和比較導讀J2SE1.4以上版本中發布了全新的I/O類庫。本文將通過一些實例來簡單介紹NIO庫提供的一些新特性&#xff1a;非阻塞I/O&#xff0c;字符轉換&#xff0c;緩沖以及通道。一. 介紹NIONIO包(java.nio.*)引入了四個關鍵的抽象數據類型&#xff0c;它們共…

Java LocalDate類| isSupported()方法與示例

LocalDate類isSupported()方法 (LocalDate Class isSupported() method) Syntax: 句法&#xff1a; public boolean isSupported (TemporalField t_field);public boolean isSupported (TemporalUnit t_unit);isSupported() method is available in java.time package. isSupp…

區塊鏈+稅務的思考

2016年&#xff0c;區塊鏈技術火了&#xff01;各大金融公司、互聯網巨頭都競相參加到區塊鏈技術的研究中。我們公司的業務是稅務的信息化領域&#xff0c;也希望通過區塊鏈技術的應用&#xff0c;來提升為財稅領域的服務。 區塊鏈技術優缺點總結 下圖是對區塊鏈技術的一些特點…

java hasset 順序_java集合排序問題

List: 元素是有序的&#xff0c;元素可以重復&#xff0c;因為該集合體系有索引(腳標)常用的子類對象&#xff1a;1————ArrayList 底層的數據結構是使用的數組結構特點&#xff1a;查詢速度快&#xff0c;但是增刪比較慢2————LinkedList底層的數據結構使用的是鏈表結構…

如何使用JavaScript刪除CSS屬性?

In this article, well see how we can remove a CSS property from a certain element using JavaScript? We can remove only those properties that we assign ourselves and the pre-default ones cannot be removed by this method. 在本文中&#xff0c;我們將看到如何使…

Django 緩存系統

Django 是動態網站&#xff0c;一般來說需要實時地生成訪問的網頁&#xff0c;展示給訪問者&#xff0c;這樣&#xff0c;內容可以隨時變化&#xff0c;但是從數據庫讀多次把所需要的數據取出來&#xff0c;要比從內存或者硬盤等一次讀出來 付出的成本大很多。 緩存系統工作原理…

java web截屏_java_WebDriver中實現對特定的Web區域截圖方法,用過 WebDriver 的同學都知道,We - phpStudy...

WebDriver中實現對特定的Web區域截圖方法用過 WebDriver 的同學都知道&#xff0c;WebDriver 可以對瀏覽器中的頁面進行截圖。例如&#xff1a;public byte[] takeScreenshot() throws IOException {TakesScreenshot takesScreenshot (TakesScreenshot) driver;return takesSc…

c語言 關鍵字const_C ++ const關鍵字| 查找輸出程序| 套裝1

c語言 關鍵字constProgram 1: 程序1&#xff1a; #include <iostream>using namespace std;void fun(int& A) const{A 10;}int main(){int X 0;fun(X);cout << X;return 0;}Output: 輸出&#xff1a; [Error] non-member function void fun(int) cannot ha…

【喜報】JEEWX榮獲“2016 年度碼云新增熱門開源軟件排行榜”第一名!

為什么80%的碼農都做不了架構師&#xff1f;>>> 2016 年度碼云新增項目排行榜 TOP 50 正式出爐&#xff01;根據 2016 年在碼云上新增開源項目的 Watch、Star、Fork 數量以及其他角度的統計&#xff0c;JEEWX捷微管家榮獲“2016 年度碼云新增熱門開源軟件排行榜”第…

java 二叉樹特點_瘋狂java筆記之樹和二叉樹

樹的概述樹是一種非常常用的數據結構&#xff0c;樹與前面介紹的線性表&#xff0c;棧&#xff0c;隊列等線性結構不同&#xff0c;樹是一種非線性結構1.樹的定義和基本術語計算機世界里的樹&#xff0c;是從自然界中實際的樹抽象而來的&#xff0c;它指的是N個有父子關系的節點…

編輯距離 dp_使用動態編程(DP)編輯距離

編輯距離 dpProblem: You are given two strings s1 and s2 of length M and N respectively. You can perform following operations on the string. 問題&#xff1a;給您兩個長度分別為M和N的字符串s1和s2 。 您可以對字符串執行以下操作。 Insert a character at any posi…

tomcat +apache 配置集群

2019獨角獸企業重金招聘Python工程師標準>>> APACHE2.2.25TOMCAT6.0.37配置負載均衡 目標: 使用 apache 和 tomcat 配置一個可以應用的 web 網站&#xff0c;要達到以下要求&#xff1a; 1. Apache 做為 HttpServer &#xff0c;后面連接多個 tomcat 應用實例&…

java雙緩存機制_詳解JVM類加載機制及類緩存問題的處理方法

前言大家應該都知道&#xff0c;當一個Java項目啟動的時候&#xff0c;JVM會找到main方法&#xff0c;根據對象之間的調用來對class文件和所引用的jar包中的class文件進行加載(其步驟分為加載、驗證、準備、解析、初始化、使用和卸載)&#xff0c;方法區中開辟內存來存儲類的運…

oracle中dbms_并發和由于DBMS中的并發導致的問題

oracle中dbms并發 (Concurrency) The ability of a database system which handles simultaneously or a number of transactions by interleaving parts of the actions or the overlapping this is called concurrency of the system. 數據庫系統通過交織部分操作或重疊操作來…

什么是mvc?

什么是MVCMVC 是一種設計模式&#xff0c;它將應用劃分為3 個部分&#xff1a;數據&#xff08;模型&#xff09;、展現層&#xff08;視圖&#xff09;和用戶交互層&#xff08;控制器&#xff09;。換句話說&#xff0c;一個事件的發生是這樣的過程&#xff1a;1&#xff0e;…

mysql的安裝和基本命令_MySQL安裝以及簡單命令用法

MYSQL:關系型數據庫存儲引擎:負責將邏輯層的概念轉化為物理層機制&#xff0c;在物理層完成物理機制。支持事務&#xff1a;transaction必須滿足的條件&#xff1a;ACID(一致性,持久性,原子性,隔離性)鎖&#xff1a;并發訪問隨機訪問&#xff1a;數據在磁盤上是隨機存儲的安裝&…

將數組轉換為JavaScript中的對象

Lets say you have the following array, 假設您有以下數組&#xff0c; const nums [1, 2, 3, 4, 5];console.log(nums);Output 輸出量 (5) [1, 2, 3, 4, 5]We know that nums is an array and we can see in the output that we get an array. Lets convert it into an ob…

docker集群運行在calico網絡上

2019獨角獸企業重金招聘Python工程師標準>>> ##網絡及版本信息 docker1 centos7 192.168.75.200 docker2 centos7 192.168.75.201 物理網絡 192.168.75.1/24 Docker version 1.10.3, build 3999ccb-unsupported &#xff0c;安裝過程略 # calicoctl version Version…