commons-collections4
库对Java标准库的集合工具类进行了一些补充,其中包含一些非常实用的方法,能够简化我们代码的编写,这里我们简单了解学习。
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-collections4</artifactId>
<version>4.4</version>
</dependency>
注:该库中最常用的CollectionUtils
和MapUtils
对应Java中的两大集合类型,实际上我们日常使用的List
和Set
实现了Collection
接口,工具类也是按此划分的。两者有很多类似的地方,因此以下主要以CollectionUtils
进行介绍。
CollectionUtils.isEmpty
可以判断集合是否为空,当传入参数为null
或大小为0的集合时,返回true
。类似的,CollectionUtils.isNotEmpty
是相反的效果。
public static boolean isEmpty( @Nullable java.util.Collection<?> coll )
public static boolean isNotEmpty( @Nullable java.util.Collection<?> coll )
求两个集合交集:
public static <O> java.util.Collection<O> intersection(
@NotNull Iterable<? extends O> a,
@NotNull Iterable<? extends O> b
)
求两个集合并集:
public static <O> java.util.Collection<O> union(
@NotNull Iterable<? extends O> a,
@NotNull Iterable<? extends O> b
)
求两个集合差集(a - b):
public static <O> java.util.Collection<O> subtract(
@NotNull Iterable<? extends O> a,
@NotNull Iterable<? extends O> b
)
判断集合a是否包含在集合b中:
public static boolean isSubCollection(
@NotNull java.util.Collection<?> a,
@NotNull java.util.Collection<?> b
)
CollectionUtils.filter
能够通过传入的回调函数对集合进行过滤,将不符合条件的元素(即predicate返回false)移除。
public static <T> boolean filter(
@Nullable Iterable<T> collection,
@Nullable org.apache.commons.collections4.Predicate<? super T> predicate
)
例子代码,筛选List中的所有偶数:
package com.gacfox.demo;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.collections4.Predicate;
import java.util.*;
public class Main {
public static void main(String[] args) {
List<Integer> list1 = new ArrayList<>(Arrays.asList(1, 2, 3, 4, 5, 6));
CollectionUtils.filter(list1, new Predicate<Integer>() {
@Override
public boolean evaluate(Integer a) {
return a % 2 == 0;
}
});
System.out.println(list1);
}
}
补充:Java8中引入了StreamAPI
,像filter
这种功能现在标准库也能够实现了。