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

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());
}