JAVA:lambda example - Predicate (3)

Rojer.2019.01.31

今天發現到 JAVA 的 Predicate 用法,感覺規則比較複雜的時候,可以用這樣的方式來簡化一下程式碼,下面是使用的範例。

資料格式

public class Item {
public String ItemName;
public String ItemNo;
public String ItemSource;
public Integer Total;
public Item(String itemName, String itemNo, String itemSource, Integer total) {
ItemName = itemName;
ItemNo = itemNo;
ItemSource = itemSource;
Total = total;
}
}

範例

public class Main {
public static void main(String[] args) {
Predicate<Item> rule1 = x -> x.ItemName.equals("Name1");
List<Item> list = new ArrayList<Item>();
Item it = new Item("Name2", "No2", "E", 25);
list.add(it);
it = new Item("Name2", "No1", "D", 20);
list.add(it);
it = new Item("Name1", "No2", "C", 15);
list.add(it);
it = new Item("Name1", "No1", "B", 5);
list.add(it);
it = new Item("Name1", "No1", "A", 10);
list.add(it);
long x1 = list.stream().filter(x ->
x.ItemName.equals("Name1")).count();
long x2 = list.stream().filter(rule1).count();
//x1 x2 結果相同
System.out.println("x1=" + x1);
System.out.println("x2=" + x2);
}
}

※延伸閱讀
JAVA:lambda example (2)
JAVA:lambda example
Java 8 系列 - 行為參數化與 Lambda 表達式

    Blogger Comment

0 意見: