# 如何在集合中筛选出满足条件的元素——org.apache.commons.collections4的使用

142人阅读 评论(0)

public static <O> Collection<O> select(Iterable<? extends O> inputCollection, Predicate<? super O> predicate)

inputCollection：被筛选的集合

Predicate：筛选的条件

### 对Predicate的理解

public class Person
{
public static final String M = "male";
public static final String FM = "female";

private String name;

private int age;

private String sex;

public Person(String name, String sex, int age)
{
this.name = name;
this.age = age;
this.sex = sex;
}
}


Predicate<Person> malePredicate = new Predicate<Person>()
{
public boolean evaluate(Person paramT)
{
return StringUtils.equals(paramT.getSex(), Person.M);
}
};


public class AgeGreateThanPredicate<T extends Person> implements Predicate<T>
{
private int age;

public AgeGreateThanPredicate(int age)
{
this.age = age;
}

public boolean evaluate(Person paramT)
{
return paramT.getAge() > age;
}
};

Predicate<Person> ageGreateThan20Predicate = new AgeGreateThanPredicate<Person>(20);


AndPredicate可以将两个Predicate进行与操作，还有NotPredicate、OrPredicate实现非与或操作

AndPredicate<Person> condition1 = new AndPredicate<Person>(malePredicate, ageGreateThan20Predicate);


@Test
public void test()
{
//集合初始化
List<Person> persons = new ArrayList<Person>();
Person p1 = new Person("A", Person.FM, 10);
Person p2 = new Person("B", Person.M, 20);
Person p3 = new Person("C", Person.FM, 25);
Person p4 = new Person("D", Person.M, 30);
Person p5 = new Person("E", Person.FM, 40);
Person p6 = new Person("F", Person.M, 50);
//筛选出男性Person
List<Person> malePerson = (List<Person>) CollectionUtils.select(persons, malePredicate);
Assert.assertEquals(3, malePerson.size());
//筛选出年龄大于20的Person
List<Person> orderThan20Person = (List<Person>) CollectionUtils.select(persons, ageGreateThan20Predicate);
Assert.assertEquals(4, orderThan20Person.size());
//筛选出年龄大于20的男性Person
AndPredicate<Person> condition1 = new AndPredicate<Person>(malePredicate, ageGreateThan20Predicate);
List<Person> condition1Person = (List<Person>) CollectionUtils.select(persons, condition1);
Assert.assertEquals(2, condition1Person.size());
}


0
0

* 以上用户言论只代表其个人观点，不代表CSDN网站的观点或立场
个人资料
• 访问：52159次
• 积分：1967
• 等级：
• 排名：千里之外
• 原创：142篇
• 转载：4篇
• 译文：10篇
• 评论：2条
文章分类
阅读排行
评论排行
最新评论
• JMockit Mockups API

lzzzl: 确实不管修饰符，也就是MOCK的时候，MOCKUP里全部写成PUBLIC就行了，这样甚至可以MOCK...