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可以充分简化集合的运算,

 

猜你喜欢

转载自www.cnblogs.com/shadow-shine/p/9704419.html