来自:小小程序员。 本文仅作记录
org.apache.commons.collections包下的CollectionUtils工具类,下面说说它的用法:
一、集合判空
通过CollectionUtils工具类的isEmpty方法可以轻松判断集合是否为空,isNotEmpty方法判断集合不为空。
List<Integer> list = new ArrayList<>();
list.add(2);
list.add(1);
list.add(3);
if (CollectionUtils.isEmpty(list)) {
System.out.println("集合为空");
}
if (CollectionUtils.isNotEmpty(list)) {
System.out.println("集合不为空");
}
二、对两个集合进行交、并、补、差集操作
List<Integer> list = new ArrayList<>();
list.add(2);
list.add(1);
list.add(3);
List<Integer> list2 = new ArrayList<>();
list2.add(2);
list2.add(4);
//获取并集
Collection<Integer> unionList = CollectionUtils.union(list, list2);
System.out.println(unionList);
//获取交集
Collection<Integer> intersectionList = CollectionUtils.intersection(list, list2);
System.out.println(intersectionList);
//获取交集的补集
Collection<Integer> disjunctionList = CollectionUtils.disjunction(list, list2);
System.out.println(disjunctionList);
//获取差集
Collection<Integer> subtractList = CollectionUtils.subtract(list, list2);
System.out.println(subtractList);
运行结果:
[1, 2, 3, 4]
[2]
[1, 3, 4]
[1, 3]
三、从一个对象的集合中,获取某一属性的集合
从一个对象的集合中,获取某一属性的集合。如,从人员信息集合中获取人员姓名的集合
List<Map<String, Object>> list = new ArrayList<>();
Map<String, Object> map1 = new HashMap<>();
map1.put("name", "张三");
map1.put("age", 1);
Map<String, Object> map2 = new HashMap<>();
map2.put("name", "李四");
map2.put("age", 2);
Map<String, Object> map3 = new HashMap<>();
map3.put("name", "王五");
map3.put("age", 3);
list.add(map1);
list.add(map2);
list.add(map3);
List<String> nameList = (List<String>) CollectionUtils.collect(
list, new Transformer() {
public Object transform(Object arg0) {
Map<String, Object> map = (Map<String, Object>) arg0;
return map.get("name");
}
});
System.out.println(nameList);
运行结果:
[张三, 李四, 王五]
四、从一个对象集合中过滤出只符合要求的对象
List<Map<String, Object>> list = new ArrayList<>();
List<Map<String, Object>> tarList = new ArrayList<>();
Map<String, Object> map1 = new HashMap<>();
map1.put("name", "张三");
map1.put("age", 1);
Map<String, Object> map2 = new HashMap<>();
map2.put("name", "张三");
map2.put("age", 2);
Map<String, Object> map3 = new HashMap<>();
map3.put("name", "王五");
map3.put("age", 3);
list.add(map1);
list.add(map2);
list.add(map3);
CollectionUtils.filter(list, new Predicate(){
public boolean evaluate(Object arg0) {
Map<String, Object> map = (Map<String, Object>)arg0;
return "张三".equals((String)map.get("name"))
&& 2 == Integer.parseInt(String.valueOf(map.get("age")));
}
});
System.out.println(list);
执行结果:
[{name=张三, age=2}]