使用Predicate操作Collection集合
Java 8 起為 Collection 集合新增了一個(gè) removeIf(Predicate filter) 方法,該方法將會批量刪除符合 filter 條件的所有元素。該方法需要一個(gè) Predicate 對象作為參數(shù),Predicate 也是函數(shù)式接口,因此可使用 Lambda 表達(dá)式作為參數(shù)。
示例使用 Predicate 來過濾集合。
public class ForeachTest {public static void main(String[] args) {// 創(chuàng)建一個(gè)集合Collection objs = new HashSet();objs.add(new String("中文百度搜索Java教程"));objs.add(new String("中文百度搜索C++教程"));objs.add(new String("中文百度搜索C語言教程"));objs.add(new String("中文百度搜索Python教程"));objs.add(new String("中文百度搜索Go教程"));// 使用Lambda表達(dá)式(目標(biāo)類型是Predicate)過濾集合objs.removeIf(ele -> ((String) ele).length() < 12);System.out.println(objs);} }上面程序中第 11 行代碼調(diào)用了 Collection 集合的 removeIf() 方法批量刪除集合中符合條件的元素,程序傳入一個(gè) Lambda 表達(dá)式作為過濾條件。所有長度小于 12 的字符串元素都會被刪除。編譯、運(yùn)行這段代碼,可以看到如下輸出:
[中文百度搜索Java教程, 中文百度搜索Python教程]使用 Predicate 可以充分簡化集合的運(yùn)算,假設(shè)依然有上面程序所示的 objs 集合,如果程序有如下三個(gè)統(tǒng)計(jì)需求:
統(tǒng)計(jì)集合中出現(xiàn)“中文百度搜索”字符串的數(shù)量。統(tǒng)計(jì)集合中出現(xiàn)“Java”字符串的數(shù)量。統(tǒng)計(jì)集合中出現(xiàn)字符串長度大于 12 的數(shù)量。此處只是一個(gè)假設(shè),實(shí)際上還可能有更多的統(tǒng)計(jì)需求。如果采用傳統(tǒng)的編程方式來完成這些需求,則需要執(zhí)行三次循環(huán),但采用 Predicate 只需要一個(gè)方法即可。下面代碼示范了這種用法。
public class ForeachTest {public static void main(String[] args) {// 創(chuàng)建一個(gè)集合Collection objs = new HashSet();objs.add(new String("中文百度搜索Java教程"));objs.add(new String("中文百度搜索C++教程"));objs.add(new String("中文百度搜索C語言教程"));objs.add(new String("中文百度搜索Python教程"));objs.add(new String("中文百度搜索Go教程"));// 統(tǒng)計(jì)集合中出現(xiàn)“中文百度搜索”字符串的數(shù)量System.out.println(calAll(objs, ele -> ((String) ele).contains("中文百度搜索")));// 統(tǒng)計(jì)集合中出現(xiàn)“Java”字符串的數(shù)量System.out.println(calAll(objs, ele -> ((String) ele).contains("Java")));// 統(tǒng)計(jì)集合中出現(xiàn)字符串長度大于 12 的數(shù)量System.out.println(calAll(objs, ele -> ((String) ele).length() > 12));}public static int calAll(Collection books, Predicate p) {int total = 0;for (Object obj : books) {// 使用Predicate的test()方法判斷該對象是否滿足Predicate指定的條件if (p.test(obj)) {total++;}}return total;} }輸出結(jié)果為:
5 1 1上面程序先定義了一個(gè) calAll() 方法,它使用 Predicate 判斷每個(gè)集合元素是否符合特定條件,條件將通過 Predicate 參數(shù)動態(tài)傳入。從上面程序中第 11、13、15 行代碼可以看到,程序傳入了 3 個(gè) Lambda 表達(dá)式,其目標(biāo)類型都是 Predicate,這樣 calAll() 方法就只會統(tǒng)計(jì)滿足 Predicate 條件的圖書。
總結(jié)
以上是生活随笔為你收集整理的使用Predicate操作Collection集合的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 不同进制之间的转化
- 下一篇: Spring使用AspectJ开发AOP