傳遞代碼
我們首先看一個例子,假設你有一個 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 );