java集合(3)-Java8新增的Predicate操作集合


Java8起為Collection集合新增了一個removeIf(Predicate filter)方法,該方法將批量刪除符合filter條件的所有元素.該方法需要一個Predicate(謂詞)對象作為參數,Predicate也是函數式接口,因此可以使用Lambda表達式作為參數.

 
        
package com.j1803.collectionOfIterator;
import java.util.Collection;
import java.util.HashSet;
public class IteratorTest {
    public static void main(String[] args) {
        //創建集合books
        Collection books=new HashSet();
        books.add("PHP");
        books.add("C++");
        books.add("C");
        books.add("Java");
        books.add("Python");
        System.out.println(books);
        //使用Lambda表達式(目標類型是Predicate)過濾集合
        books.removeIf(ele->((String)ele).length()<=3);
        System.out.println(books);

    }
}
 
        

調用集合Collection的removeIf()方法批量刪除符合條件的元素,程序傳入一個Lambda表達式作為過濾條件:所有長度小於等於3的字符串元素都會被刪除.運行結果為:

[Java, C++, C, PHP, Python]
[Java, Python]

Process finished with exit code 0

使用Predicate可以充分簡化集合的運算,

public class IteratorTest {
    public static void main(String[] args) {
        //創建集合books
        Collection books=new HashSet();
        books.add("PHP");
        books.add("C++");
        books.add("C");
        books.add("Java");
        books.add("Python");
        System.out.println(books);
        //統計書名包括出現"C"字符串的次數
        System.out.println(calAll(books,ele->((String)ele).contains("C")));
    }
    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;
    }
}
[Java, C++, C, PHP, Python]
2

Process finished with exit code 0

calAll()方法會統計滿足Predicate條件的圖書.

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM