欢迎关注作者博客
简书传送门

文章目录

  • 前言
  • 代码示例

前言

阅读源码的重要性,后期会对各大开源框架相关源码做详细阅读,并熟悉使用,本次主要对Apache Commons Collections中CollectionUtils类进行示例分析,如有错误,请多指教。


通过apache-commons包中的org.apache.commons.collections.CollectionUtils集合操作工具类 对集合间进行合并union、交叉intersection、分离disjunction、减去subtract、任意包含containsAny、判断是否为子集isSubCollection、颠倒序列reverseArray及判断是否填满isFull等操作。

代码示例

package com.zzx.apache.commons.chapter1;import lombok.Data;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.collections.Transformer;
import org.junit.jupiter.api.Test;import java.util.*;/*** <p>* 通过apache-commons包中的org.apache.commons.collections.CollectionUtils集合操作工具类 对集合间进行合并union、交叉intersection、分离disjunction、减去subtract、任意包含containsAny、* 判断是否为子集isSubCollection、颠倒序列reverseArray及判断是否填满isFull等操作。* </p>**/
public class CollectionsUtilsDemo {/** Arrays.asList()返回的是Arrays内部类ArraysList,不可对其进行add、remove等操作,返回报UnsupportedOperationException *//** java.util.ArrayList和Arrays内部类ArraysList都继承AbstractList,remove、add等方法AbstractList中是默认throw UnsupportedOperationException而且不作任何操作。*//** java.util.ArrayList重新了这些方法而Arrays的内部类ArrayList没有重新,所以会抛出异常。*/// @Deprecated// private static List<String> list1 = Arrays.asList(new String[] {"1", "2", "3", "1"});// @Deprecated// private static List<String> list2 = Arrays.asList(new String[] {"2", "3", "4"});// @Deprecated// private static List<String> list3 = Arrays.asList(new String[] {"1", "2"});/** 解决 */private static List<String> list1 = new ArrayList<>(Arrays.asList(new String[] {"1", "2", "3", "1", "5"}));private static List<String> list2 = new ArrayList<>(Arrays.asList(new String[] {"2", "3", "1"}));private static List<String> list3 = new ArrayList<>(Arrays.asList(new String[] {"1", "2"}));@Dataclass Employee {private String name;private String email;private int age;private double salary;/** 是否在职 */private boolean activeEmployee;public Employee(String name, String email, int age, double salary, boolean activeEmployee) {this.name = name;this.email = email;this.age = age;this.salary = salary;this.activeEmployee = activeEmployee;}}/*** 判断两个集合是否和相同元素*/public void containsAnyT1() {// 判断两个集合是否和相同元素boolean b = CollectionUtils.containsAny(list1, list2);System.out.println(b);}/*** 得到两个集合中相同的元素*/@Testpublic void intersectionT1() {Collection b = CollectionUtils.intersection(list1, list2);System.out.println(b);}/*** 合并两个集合,不去重*/@Testpublic void unionT1() {Collection b = CollectionUtils.union(list1, list2);System.out.println(b);}/*** 取两个集合差集,不去重*/@Testpublic void disjunctionT1() {Collection b = CollectionUtils.disjunction(list1, list2);System.out.println(b);}/*** list1 - list2 = 剩余元素组成的集合*/@Testpublic void subtractT1() {// Collection b = CollectionUtils.subtract(list1, list2);Collection b = CollectionUtils.subtract(list2, list1);System.out.println(b);}/*** 统计集合中各元素出现的次数,并Map<Object, Integer>输出*/@Testpublic void getCardinalityMapT1() {Map cardinalityMap = CollectionUtils.getCardinalityMap(list1);cardinalityMap.forEach((k, v) -> System.out.println(k + ":" + v));}/*** a是否b集合子集,a集合大小<=b集合大小*/@Testpublic void isSubCollectionT1() {// boolean subCollection = CollectionUtils.isSubCollection(list3, list1);boolean subCollection = CollectionUtils.isSubCollection(list3, list2);System.out.println(subCollection);}/*** a是否b集合子集,a集合大小<b集合大小*/@Testpublic void isProperSubCollectionT1() {// boolean subCollection = CollectionUtils.isSubCollection(list3, list1);boolean subCollection = CollectionUtils.isProperSubCollection(list3, list2);System.out.println(subCollection);}/*** 两个集合是否相同*/@Testpublic void isEqualCollectionT1() {boolean subCollection = CollectionUtils.isSubCollection(list1, list1);// boolean subCollection = CollectionUtils.isEqualCollection(list3, list2);System.out.println(subCollection);}/*** 某元素在集合中出现的次数*/@Testpublic void cardinalityT1() {int cardinality = CollectionUtils.cardinality("1", list1);System.out.println(cardinality);}/*** 返回集合中满足函数式的唯一元素,只返回最先处理符合条件的唯一元素*/@Testpublic void findT1() {Object o = CollectionUtils.find(list1, e -> Integer.parseInt(e.toString()) > 2);System.out.println(o.toString());}/*** 对集合中的对象中的某一属性进行批量更新,closure为需要更新的属性对象* 如对集合中所有员工的加薪20%*/@Testpublic void forAllDoT1() {// // create the closure// List<Employee> employees = new ArrayList<>();// Employee e1 = new Employee("e1", "e1.com", 21, 10000, true);// Employee e2 = new Employee("e2", "e2.com", 22, 14000, false);// Employee e3 = new Employee("e3", "e3.com", 23, 12000, true);// Employee e4 = new Employee("e4", "e4.com", 21, 12000, true);// Closure<E> closure = new Closure() {//     @Override//     public void execute(Employee e) {//         e.setSalary(e.getSalary() * 1.2);//     }// };}/*** 过滤集合中满足函数式的所有元素*/@Testpublic void filterT1() {CollectionUtils.filter(list1, e -> Integer.parseInt(e.toString()) > 1);list1.forEach(s -> {System.out.println(s);});}/*** 转换新的集合,对集合中元素进行操作,如每个元素都累加1*/@Testpublic void transformT1() {CollectionUtils.transform(list1, new Transformer() {@Overridepublic Object transform(Object o) {Integer num = Integer.parseInt((String)o);return String.valueOf(++num);}});list1.forEach(s -> {System.out.println(s);});System.out.println("============================");// JDK8List<String> temp = new ArrayList<>();list1.stream().forEach(i -> {int num = Integer.parseInt(i);temp.add(String.valueOf(num));});temp.forEach(System.out::println);}/*** 返回集合中满足函数式的数量*/@Testpublic void countMatchesT1() {int num = CollectionUtils.countMatches(list1, i -> Integer.parseInt((String)i) > 0);System.out.println(num);}/*** 将满足表达式的元素存入新集合中并返回新集合元素对象*/@Testpublic void selectT1() {Collection select = CollectionUtils.select(list1, i -> Integer.parseInt((String)i) > 2);select.forEach(System.out::println);}/*** 将不满足表达式的元素存入新集合中并返回新集合元素对象*/@Testpublic void selectRejectedT1() {Collection select = CollectionUtils.selectRejected(list1, i -> Integer.parseInt((String)i) > 2);select.forEach(System.out::println);}/*** collect底层调用的transform方法* 将所有元素进行处理,并返回新的集合*/@Testpublic void collectT1() {Collection collecttion = CollectionUtils.collect(list1, new Transformer() {@Overridepublic Object transform(Object o) {int i = Integer.parseInt((String)o);return ++i;}});collecttion.forEach(System.out::println);}/*** 将一个数组或集合中的元素全部添加到另一个集合中*/@Testpublic void adAllT1() {CollectionUtils.addAll(list1, new String[]{"5", "6"});CollectionUtils.addAll(list1, list2.toArray());list1.forEach(System.out::println);}/*** 返回集合中指定下标元素*/@Testpublic void indexT1() {String index = (String)CollectionUtils.index(list1, 2);System.out.println(index);}/*** 返回集合中指定下标元素*/@Testpublic void getT1() {String index = (String)CollectionUtils.get(list1, 2);System.out.println(index);}/*** 判断集合是否为空*/@Testpublic void isEmptyT1() {int[] arr = new int[5];arr[0] = 1;arr[1] = 1;arr[2] = 1;arr[3] = 1;arr[4] = 1;boolean empty = CollectionUtils.isFull(new ArrayList(Arrays.asList(arr)));System.out.println(empty);}/*** 判断集合是否为空*/@Testpublic void isFullT1() {boolean full = CollectionUtils.isFull(list1);System.out.println(full);}/*** 返回集合最大空间*/@Testpublic void maxSizeT1() {// List<Integer> boundedList = new ArrayList<>(8);// int i = CollectionUtils.maxSize(boundedList);// System.out.println(i);}/*** 只要集合中元素不满足表达式就抛出异常*/@Testpublic void predicatedCollectionT1() {Collection collection = CollectionUtils.predicatedCollection(list1, i -> Integer.parseInt((String)i) > 1);collection.forEach(System.out::println);}/*** 只要集合中元素不满足表达式就抛出异常*/@Testpublic void removeAllT1() {boolean b = list1.removeAll(list2);System.out.println(b);list1.forEach(System.out::println);}/*** 只要集合中元素不满足表达式就抛出异常*/@Testpublic void synchronizedCollectionT1() {Collection collection = CollectionUtils.synchronizedCollection(list1);collection.forEach(System.out::println);}/*** 只要集合中元素不满足表达式就抛出异常*/@Testpublic void unmodifiedCollectionT1() {Collection collection = CollectionUtils.unmodifiableCollection(list1);collection.forEach(System.out::println);}/*** 只要集合中元素不满足表达式就抛出异常*/@Testpublic void predicatedCollectionT2() {// Collection collection = CollectionUtils.predicatedCollection(list1, i -> Integer.parseInt((String)i) > 0);// Collection collection = CollectionUtils.typedCollection(list1, String.class);Collection collection = CollectionUtils.transformedCollection(list1, new Transformer() {@Overridepublic Object transform(Object o) {int n = Integer.parseInt((String)o);return n + n;}});collection.forEach(System.out::println);}}

欢迎加入Java猿社区! 免费领取我历年收集的所有学习资料哦!

Java猿社区—Apache Commons Collections—CollectionUtils工具类详解相关推荐

  1. apache commons collections CollectionUtils工具类简单使用

    CollectionUtils提供很多对集合的操作方法,常用的方法如下 不仅可以判断Collection集合类,还可以判断JSONArray是否为空. import org.apache.common ...

  2. mongodb java 单例_JAVA单例MongoDB工具类详解

    shasha 2018年09月07日 681 0 JAVA单例MongoDB工具类 JAVA驱动版本: org.mongodb mongo-java-driver 3.0.2 工具类代码如下: pac ...

  3. java 汉字 数字_java数字转汉字工具类详解

    /** * Created by 33303 on 2017/7/28. */ import java.math.BigDecimal; /** * 数字转换为汉语中人民币的大写 * */ publi ...

  4. Apache commons lang3 StringUtils工具类

    Apache commons lang3 StringUtils工具类 Apache commons lang3包下的StringUtils工具类中封装了一些字符串操作的方法,非常实用,使用起来也非常 ...

  5. Android复习14【高级编程:推荐网址、抠图片上的某一角下来、Bitmap引起的OOM问题、三个绘图工具类详解、画线条、Canvas API详解(平移、旋转、缩放、倾斜)、矩阵详解】

    目   录 推荐网址 抠图片上的某一角下来 8.2.2 Bitmap引起的OOM问题 8.3.1 三个绘图工具类详解 画线条 8.3.16 Canvas API详解(Part 1) 1.transla ...

  6. Android基础入门教程——8.3.1 三个绘图工具类详解

    Android基础入门教程--8.3.1 三个绘图工具类详解 标签(空格分隔): Android基础入门教程 本节引言: 上两小节我们学习了Drawable以及Bitmap,都是加载好图片的,而本节我 ...

  7. Apache Commons包 StringUtils工具类深入整理(转载)

    [转载地址]:cnblogs.com/sealy321/p/10227131.html 字符串是在程序开发中最常见的,Apache Commons开源项目在org.apache.commons.lan ...

  8. java外部接口图解_java代码实现访问网络外部接口并获取数据的工具类详解

    java代码实现访问网络外部接口并获取数据的工具类 工具类代码,可以直接copy使用 package com.yqzj.util; import org.apache.log4j.LogManager ...

  9. Java多线程系列(九):CountDownLatch、Semaphore等4大并发工具类详解

    之前谈过高并发编程系列:4种常用Java线程锁的特点,性能比较.使用场景 ,以及高并发编程系列:ConcurrentHashMap的实现原理(JDK1.7和JDK1.8) 今天主要介绍concurre ...

最新文章

  1. PPT模板中的”书签”
  2. Elastic 使用Heartbeat监测服务运行状态
  3. InputStream 、 InputStreamReader 、 BufferedReader区别
  4. 今天我注册博客园了,我很开心!
  5. 结合webpack配置_呕心沥血编写的webpack多入口零基础配置 【建议收藏】
  6. 多分辨率下的彩色图像分割方法
  7. 设置指定ip访问mysql数据库
  8. git 下载指定历史版本
  9. SOLID 原则之依赖倒置原则
  10. 年轻人逃离一线城市:外地人生存环境愈发严峻
  11. C++判断两个链表是否相交算法
  12. 51单片机期末课程作业之蓝牙、操控、测速、里程小车
  13. 智能路由器VS传统路由器:未来由谁主宰?
  14. 如何写一篇人工智能领域的期刊论文(SCI论文的固定模式和一些套路)
  15. 如何在pycharm中安装PIL模块
  16. JSP学习---jsp简介和理解jsp的本质
  17. visual svn使用教程
  18. code engine
  19. linux7开启ntp服务,CentOS7/Red Hat7 NTP服务无法开机自启动
  20. APS软件的技术指标与特色

热门文章

  1. 全职宝妈卖出去5万多元的保暖袜子 只用这一招截流
  2. symbian与uiq开发教程之一-初识symbian(转)
  3. Python 点滴 V
  4. 玉帝传美猴王上天,大闹天宫之Java设计模式:命令模式
  5. 芯片生产测试中的CP wafer单片测试时间和UPH预估
  6. Data Whale第20期组队学习 Pandas学习—第一次综合练习
  7. XXX正在运行,点按即可了解详情或停止应用
  8. 实现isPrime()函数,参数为整数,要有异常处理。如果整数是质数,返回True,否则返回False
  9. Bootstrap系列之卡片(Cards)
  10. Canvas画钟 js