Apache Commons Collections库的CollectionUtils
类提供各种实用方法,用于覆盖广泛用例的常见操作。 它有助于避免编写样板代码。 这个库在jdk 8之前是非常有用的,但现在Java 8的Stream API提供了类似的功能。
使用filter()方法过滤列表
CollectionUtils的filter()
方法可用于过滤列表以移除不满足由谓词传递提供的条件的对象。
声明
以下是org.apache.commons.collections4.CollectionUtils.filter()
方法的声明 -
public static <T> boolean filter(Iterable<T> collection,
Predicate<? super T> predicate)
- collection - 从中获取输入的集合可能不为
null
。 - predicate - 用作过滤器的
predicate
可能为null
。
返回值
如果通过此调用修改了集合,则返回true
,否则返回false
。
示例
以下示例显示org.apache.commons.collections4.CollectionUtils.filter()
方法的用法。 这个示例中将过滤一个整数列表来获得偶数。
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.collections4.Predicate;
public class CollectionUtilsTester {
public static void main(String[] args) {
List<Integer> integerList = new ArrayList<Integer>();
integerList.addAll(Arrays.asList(1,2,3,4,5,6,7,8));
System.out.println("Original List: " + integerList);
CollectionUtils.filter(integerList, new Predicate<Integer>() {
@Override
public boolean evaluate(Integer input) {
if(input.intValue() % 2 == 0) {
return true;
}
return false;
}
});
System.out.println("Filtered List (Even numbers): " + integerList);
}
}
执行上面示例代码,得到以下结果 -
Original List: [1, 2, 3, 4, 5, 6, 7, 8]
Filtered List (Even numbers): [2, 4, 6, 8]
使用filterInverse()方法过滤列表
CollectionUtils的filterInverse()
方法可用于过滤列表以移除满足谓词传递提供的条件的对象。
声明
以下是org.apache.commons.collections4.CollectionUtils.filterInverse()
方法的声明 -
public static <T> boolean filterInverse(Iterable<T> collection,
Predicate<? super T> predicate)
参数
collection
- 从中获取输入的集合,可能不为null
。predicate
- 用作过滤器的predicate
可能为null
。
返回值
如果通过此调用修改了集合,则返回true
,否则返回false
。
示例
以下示例显示org.apache.commons.collections4.CollectionUtils.filterInverse()
方法的用法。 这个示例中将过滤一个整数列表来获得奇数。
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.collections4.Predicate;
public class CollectionUtilsTester {
public static void main(String[] args) {
List<Integer> integerList = new ArrayList<Integer>();
integerList.addAll(Arrays.asList(1,2,3,4,5,6,7,8));
System.out.println("Original List: " + integerList);
CollectionUtils.filterInverse(integerList, new Predicate<Integer>() {
@Override
public boolean evaluate(Integer input) {
if(input.intValue() % 2 == 0) {
return true;
}
return false;
}
});
System.out.println("Filtered List (Odd numbers): " + integerList);
}
}
执行上面示例代码,得到以下结果 -
Original List: [1, 2, 3, 4, 5, 6, 7, 8]
Filtered List (Odd numbers): [1, 3, 5, 7]