集合CollectionUtils常用函数以及差集、交集、并集

依赖:commons-collections4
包:org.apache.commons.collections.CollectionUtils;

常用判空函数
CollectionUtils.isEmpty()
CollectionUtils.isNotEmpty(Collection <?> coll)

其他函数
/** 1、除非元素为null,否则向集合添加元素 */
CollectionUtils.addIgnoreNull(personList,null)

/** 2、将两个已排序的集合a和b合并为一个已排序的列表,以便保留元素的自然顺序 */
CollectionUtils.collate(Iterable<? extends O> a, Iterable<? extends O> b)

/** 3、将两个已排序的集合a和b合并到一个已排序的列表中,以便保留根据Comparator c的元素顺序。 */
CollectionUtils.collate(Iterable<? extends O> a, Iterable<? extends O> b, Comparator<? super O> c)

/** 4、返回该个集合中是否含有至少有一个元素 */
CollectionUtils.containsAny(Collection<?> coll1, T… coll2)

/** 5、如果参数是null,则返回不可变的空集合,否则返回参数本身。(很实用 ,最终返回List EMPTY_LIST = new EmptyList<>()) */
CollectionUtils.emptyIfNull(Collection collection)

/** 6、空安全检查指定的集合是否为空 */
CollectionUtils.isEmpty(Collection <?> coll)

/** 7、 空安全检查指定的集合是否为空。 */
CollectionUtils.isNotEmpty(Collection <?> coll)

/** 8、反转给定数组的顺序。 */
CollectionUtils.reverseArray(Object[] array)

/** 9、差集 */
CollectionUtils.subtract(Iterable<? extends O> a, Iterable<? extends O> b)

/** 10、并集 */
CollectionUtils.union(Iterable<? extends O> a, Iterable<? extends O> b)

/** 11、交集 */
CollectionUtils.intersection(Collection a, Collection b)

/** 12、 交集的补集(析取) */
CollectionUtils.disjunction(Collection a, Collection b)

对象集合交、并、差处理

List personList = Lists.newArrayList();
Person person1 = new Person(“小小”, 15);
Person person2 = new Person(“中中”, 16);
personList.add(person1);
personList.add(person2);

List person1List = Lists.newArrayList();
Person person3 = new Person(“中中”, 16);
Person person4 = new Person(“大大”, 17);
person1List.add(person3);
person1List.add(person4);

/** 1、差集 */
System.out.println(CollectionUtils.subtract(personList,person1List));
//输出:[Person{name=‘小小’, age=15}]

/** 2、交集 */
System.out.println(CollectionUtils.intersection(personList,person1List));
//输出:[Person{name=‘中中’, age=16}]

/** 3、并集 */
System.out.println(CollectionUtils.union(personList,person1List));
//输出:[Person{name=‘小小’, age=15}, Person{name=‘大大’, age=17}, Person{name=‘中中’, age=16}]

/** 4、交集的补集(析取) */
System.out.println(CollectionUtils.disjunction(personList,person1List));
//输出:[Person{name=‘小小’, age=15}, Person{name=‘大大’, age=17}]

  • 3
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Java知识技术分享

感谢支持!

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值