您的位置:首页 > 编程语言 > Java开发

使用Java8新增的Predicate操作集合

2016-09-20 18:13 381 查看
使用Java8新增的Predicate操作集合:

java8为Collection集合新增了一个removeIf(Predicate filter) 方法,该方法将会批量删除符合filter条件的所有元素。

import java.util.Collection;
import java.util.HashSet;

import javax.sql.rowset.Predicate;

public class PredicateTest {

public static void main(String[] args){
//创建集合,为集合添加元素
Collection books=new HashSet();
books.add(new String("林肯公园" ));
books.add(new String("林肯公园演唱会" ));
books.add(new String("西城男孩" ));
books.add(new String("村上春树" ));
books.add(new String("林徽因" ));
books.add(new String("乔布斯可以" ));
books.add(new String("华为手机可以" ));
books.add(new String("霍元甲" ));
books.add(new String("孙悟空的七十二变" ));

//统计包含  林肯  的字符串数量
System. out.println( calAll(books,ele->((String)ele).contains("林肯" )));
//统计字符串长度大于10的字符串数量
System. out.println( calAll(books,ele->((String)ele).length()>10));
}

public static int  calAll(Collection books ,Predicate p )
{
int total =0;
for(Object obj : books)
{
//使用Predicate的test()方法判断该对象是否满足Predicate指定的条件
if( p. test(obj))
{
total++;
}
}
}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  java