您的位置:首页 > 运维架构 > Apache

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

2016-05-30 22:15 716 查看
如何在集合中筛选出满足条件的元素——org.apache.commons.collections4的使用

原来在一个集合中选出满足条件的元素:遍历 - 判断条件 - add到新的集合。

使用org.apache.commons.collections4的集合工具类CollectionUtils中的select方法

API:http://commons.apache.org/proper/commons-collections/javadocs/api-release/org/apache/commons/collections4/CollectionUtils.html

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


inputCollection:被筛选的集合

Predicate:筛选的条件

对Predicate的理解

http://commons.apache.org/proper/commons-collections/javadocs/api-release/org/apache/commons/collections4/Predicate.html

抽象接口,实现对一个对象if条件判断,该接口只有一个方法boolean evaluate(T paramT);返回true或false,即是否满足条件

例子:

要实现对
List<Person>
的筛选

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用于判断是否性别sex为male,这里使用了匿名内部类

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


定义并实例化一个Predicate用于判断年龄大于某个值

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);
persons.add(p1);
persons.add(p2);
persons.add(p3);
persons.add(p4);
persons.add(p5);
persons.add(p6);
//筛选出男性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());
}


使用该方法可以简化代码量,同时对于复合条件筛选处理更加方便灵活。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: