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条件的图书.

 
原文地址:https://www.cnblogs.com/shadow-shine/p/9704419.html