Java的CollectionUtils工具类详解

CollectionUtils工具类是在apache下的,而不是springframework下的CollectionUtils 个人觉得在真实项目中CollectionUtils,可以使你的代码更加简洁和安全 下面我们就一起来探究一下 先从maven官方找到最新jar包如下:

  1.      <!– https://mvnrepository.com/artifact/org.apache.commons/commons-collections4 –>
  2.          <dependency>
  3.              <groupId>org.apache.commons</groupId>
  4.              <artifactId>commons-collections4</artifactId>
  5.              <version>4.4</version>
  6.          </dependency>

一、API常用方法

  1.      /** 1、除非元素为null,否则向集合添加元素 */
  2. CollectionUtils.addIgnoreNull(personList,null);
  3. /** 2、将两个已排序的集合a和b合并为一个已排序的列表,以便保留元素的自然顺序 */
  4. CollectionUtils.collate(Iterable<? extends O> a, Iterable<? extends O> b)
  5. /** 3、将两个已排序的集合a和b合并到一个已排序的列表中,以便保留根据Comparator c的元素顺序。 */
  6. CollectionUtils.collate(Iterable<? extends O> a, Iterable<? extends O> b, Comparator<? super O> c)
  7. /** 4、返回该个集合中是否含有至少有一个元素 */
  8. CollectionUtils.containsAny(Collection<?> coll1, T coll2)
  9. /** 5、如果参数是null,则返回不可变的空集合,否则返回参数本身。(很实用 ,最终返回List EMPTY_LIST = new EmptyList<>()) */
  10. CollectionUtils.emptyIfNull(Collection<T> collection)
  11. /** 6、空安全检查指定的集合是否为空 */
  12. CollectionUtils.isEmpty(Collection <?> coll)
  13. /** 7、 空安全检查指定的集合是否为空。 */
  14. CollectionUtils.isNotEmpty(Collection <?> coll)
  15. /** 8、反转给定数组的顺序。 */
  16. CollectionUtils.reverseArray(Object[] array);
  17. /** 9、差集 */
  18. CollectionUtils.subtract(Iterable<? extends O> a, Iterable<? extends O> b)
  19. /** 10、并集 */
  20.      CollectionUtils.union(Iterable<? extends O> a, Iterable<? extends O> b)
  21. /** 11、交集 */
  22. CollectionUtils.intersection(Collection a, Collection b)
  23. /** 12、 交集的补集(析取) */
  24.      CollectionUtils.disjunction(Collection a, Collection b)

二、非对象集合交、并、差处理

对于集合取交集、并集的处理其实有很多种方式,这里就介绍3种

  • 第一种 是CollectionUtils工具类
  • 第二种 是List自带方法
  • 第三种 是JDK1.8 stream新特性

1、CollectionUtils工具类

下面对于基本数据(包括String)类型中的集合进行demo示例

  1.      public static void main(String[] args) {
  2.          String[] arrayA = new String[]{“1”,“2”,“3”,“4”};
  3.          String[] arrayB = new String[]{“3”,“4”,“5”,“6”};
  4.          List<String> listA = Arrays.asList(arrayA);
  5.          List<String> listB = Arrays.asList(arrayB); //1、并集 union
  6.          System.out.println(CollectionUtils.union(listA,listB)); //输出:[1, 2, 3, 4, 5, 6] //2、交集intersection
  7.          System.out.println(CollectionUtils.intersection(listA,listB)); //输出:[3, 4] //3、交集的补集(析取)disjunction
  8.          System.out.println(CollectionUtils.disjunction(listA,listB)); //输出:[1, 2, 5, 6] //4、差集(扣除)
  9.          System.out.println(CollectionUtils.subtract(listA,listB)); //[1, 2]
  10. }

2、List自带方法

  1.      public static void main(String[] args) {
  2.          String[] arrayA = new String[]{“1”,“2”,“3”,“4”};
  3.          String[] arrayB = new String[]{“3”,“4”,“5”,“6”};
  4.          List<String> listA = Arrays.asList(arrayA);
  5.          List<String> listB = Arrays.asList(arrayB); //1交集
  6.          List<String> jiaoJiList = new ArrayList<>(listA);
  7.          jiaoJiList.retainAll(listB);
  8.          System.out.println(jiaoJiList); //输出:[3, 4] //2差集
  9.          List<String> chaJiList = new ArrayList<>(listA);
  10.          chaJiList.removeAll(listB);
  11.          System.out.println(chaJiList); //输出:[1, 2] //3并集(先做差集在做添加所有)
  12.          List<String> bingList = new ArrayList<>(listA);
  13.          bingList.removeAll(listB);//[1,2]
  14.          bingList.addAll(listB);//[3,4,5,6]
  15.          System.out.println(bingList); //输出:[1, 2, 3, 4, 5, 6]
  16. }

注意:intersection和retainAll的差别

要注意的是它们返回类型是不一样的,intersection返回的是一个新的List集合,而retainAll返回是Bollean类型就说明retainAll方法是对原有集合进行处理再返回原有集合,会改变原有集合中的内容

  • 1:从性能角度来考虑的话,List自带会高点,因为它不用再创建新的集合,
  • 2:需要注意的是,因为retainAll因为会改变原有集合,所以该集合需要多次使用就不适合用retainAll

注意:Arrays.asList将数据转集合不能进行add和remove操作

原因:调用Arrays.asList()生产的List的add、remove方法时报异常,这是由Arrays.asList()返回的是Arrays的内部类ArrayList,而不是Java.util.ArrayList.Arrays的内部类ArrayList和java.util.ArrayList都是继承AbstractList,remove,add

等方法AbstractList中是默认throw UnsupportedOperationException而且不做任何操作,java.util.ArrayList重新了这些方法而Arrays的内部类没有重新,所以会抛出异常

所以正确做法如下:

String[] array = {“1”,“2”,“3”}; List list = Arrays.asList(array); List arrList = new ArrayList(list); arrList.add(“4”);

3、JDK1.8 stream新特性

  1. public static void main(String[] args) {
  2.          String[] arrayA=new String[]{“1”,“2”,“3”,“4”};
  3.          String[] arrayB=new String[]{“3”,“4”,“5”,“6”};
  4.          List<String> listA = Arrays.asList(arrayA);
  5.          List<String> listB = Arrays.asList(arrayB); //交集
  6.          List<String> intersection = listA.stream().filter(item -> listB.contains(item)).collect(Collectors.toList());
  7.          System.out.println(intersection); //输出:[3, 4] //并集(新建集合:1、是因为不影响原始集合,2、 Arrays.asList不能add和remove操作)
  8.          List<String> listAll = listA.parallelStream().collect(Collectors.toList());
  9.          List<String> listAll2 = listB.parallelStream().collect(Collectors.toList());
  10.          listAll.addAll(listAll2);
  11.          System.out.println(listAll); //输出:[1, 2, 3, 4, 3, 4, 5, 6] //差集
  12.          List<String> reduceList = listA.stream().filter(item -> !listB.contains(item)).collect(Collectors.toList());
  13.          System.out.println(reduceList); //输出:[1, 2] //去重并集
  14.          ArrayList<String> list = new ArrayList<>(listA);
  15.          list.addAll(listB);
  16.          List<String> listAllDistinct = list.stream().distinct().collect(Collectors.toList());
  17.          System.out.println(listAllDistinct); //输出:[1, 2, 3, 4, 5, 6]
  18. }

总结:三种方式,第一种稍微好用一些,第二种还需要确定该集合是否被多次调用,第三种可读性不高

三、对象集合交、并、差处理 |

因为对象的equals比较是比较两个对象的内存地址,所以除非是同一对象,否则equals返回的永远是false

但实际开发中,业务系统中判断对象有时候需要的不是一种严格意义上的相等,而是业务上的对象相等,在这种情况下,原生的equals方法就不能满足我们的需求了,所以这个时候我们需要重写equals方法

说明:String为什么可以使用equals方法,只要字符串相等就为true,那是因为String类重写了equals和hashCode方法,比较的是值

1、Person对象

  1. public static void main(String[] args) {
  2.          List<Person> personList = Lists.newArrayList();
  3.          Person person1 = new Person(“小小”, 15);
  4.          Person person2 = new Person(“中中”, 16);
  5.          personList.add(person1);
  6.          personList.add(person2);
  7.          List<Person> person1List = Lists.newArrayList();
  8.          Person person3 = new Person(“中中”, 16);
  9.          Person person4 = new Person(“大大”, 17);
  10.          person1List.add(person3);
  11.          person1List.add(person4);
  12.          /** 1、差集 */
  13.          System.out.println(CollectionUtils.subtract(personList,person1List)); //输出:[Person{name=’小小’, age=15}]
  14.          /** 2、交集 */
  15.          System.out.println(CollectionUtils.intersection(personList,person1List)); //输出:[Person{name=’中中’, age=16}]
  16.              /** 3、并集 */
  17.          System.out.println(CollectionUtils.union(personList,person1List)); //输出:[Person{name=’小小’, age=15}, Person{name=’大大’, age=17}, Person{name=’中中’, age=16}]
  18.              /** 4、交集的补集(析取) */
  19.          System.out.println(CollectionUtils.disjunction(personList,person1List)); //输出:[Person{name=’小小’, age=15}, Person{name=’大大’, age=17}]
  20. }

其他两种方式就不测了,因为都一样

四、为什么要重写equals方法一定要重写hashCode方法 |

1、源码

其实上面的Person类我可以只重写equals方法而不写hashCode方法,一样能达到上面的效果,但为什么建议写上呢?官方说法:对象的equals方法被重写,那么对象的hashCode的也尽量重写

重写equals方法就必须重写hashCode的方法的原因,从源头Object类讲起就更好理解了

先来看Object关于hashCode()和equals()的源码:

  1. public native int hashCode();
  2. public boolean equals(Object obj){
  3.      return (this == obj);
  4. }

光从代码中可以知道,hashCode方法是一个本地native方法,返回的是对象引用中存储对象的内存地址,而equals方法是利用==来比较也是对象的内存地址,从上面看出,hashCode方法和equals方法是一致的,还有最关键的一点

我们来Object类中关于hashCode方法的注释

1.在java应用程序运行期间,在对同一对象多次调用hashCode方法时,必须一致地返回相同的整数,前提是将对象进行equals比较时所用的信息没有被修改。

2.如果根据equals(Object)方法,两个对象是相等的,那么对这两个对象调用hashCode方法都必须生成相同的整数结果。

3.如果根据equals(java.lang.Object)方法,两个对象不相等,那么对这两个对象中的任一对象上调用hashCode方法不 要求一定生成不同的整数结果,但是,我们应该意识到,为不相等的对象生成不同整数结果可以提高哈希表的性能

整理:hashCode和equals保持一致,如果equals方法返回true,那么两个对象的hashCode返回值必须一样,如果equals方法返回false,hashCode可以不一样,但是这样不利于哈希表的性能,一般我们也不要这样做

假设两个对象,重写了其equals方法,其相等条件是某属性相等,就返回true,如果不重写hashCode方法,其返回的依然是两个对象的内存地址值,必然不相等,这就出现了equals方法相等,但是hashCode不相等的情况,这不符合hashCode的规则

2、HashSet和Map集合类型

重写equals方法就必须重写hashCode方法主要是针对HashSet和Map集合类型,而对于List集合到没有什么影响

原因:在向HashSet集合中存入一个元素时,HashSet会调用该对象(存入对象)的hashCode方法来得到该对象的hashCode值,然后根据该hashCode值决定该对象在HashSet中存储的位置,简单的说:

HashSet集合判断两个元素相等的标准是:两个对象通过equals方法比较相等,并且两个对象hashCode方法返回值也相等,如果两个元素通过equals方法比较返回true,但是它们的hashCode方法返回值不同,HashSet会把它们存储在不同的位置,依然可以添加成功

这就是问题所在:就是如果你只重写equals方法,而不重写hashCode,如果equals为true,而它们的hashCode方法返回值肯定不一样,因为它们都不是同一对象所以内存地址肯定不一样,所以它还是添加成功了,那么其实你写的equals方法根本没啥软用

3、代码示例

1、People类

重写equals方法,但并没有hashCode方法

  1. public class People {
  2.      private String name;
  3.      private Integer age;
  4.      public People(String name, Integer age) {
  5.          this.name = name;
  6.          this.age = age;
  7.      }
  8.      /** 重写equals方法
  9.          * @param o
  10.          * @return
  11.          */
  12. @Override
  13. public boolean equals(Object o) {
  14.      if (this == o) return true;
  15.      if (== null || getClass() != o.getClass()) return false;
  16.      People people = (People) o;
  17.      return Objects.equals(name, people.name) && Objects.equals(age, people.age);
  18. }
  19. /** * 重写toString方法
  20.          * @return
  21.          */
  22. @Override
  23. public String toString() {
  24.      return “People{“ +
  25.                  “name='” + name + ‘\” +
  26.                  “, age=” + age +
  27.                  ‘}’;
  28.      }
  29. }

main:

  1. public static void main(String[] args) {
  2.          HashSet<People> hashSet = Sets.newHashSet();
  3.          People people1 = new People(“小小”,3);
  4.          People people2 = new People(“中中”,4);
  5.          People people3 = new People(“中中”,4);
  6.          People people4 = new People(“大大”,5);
  7.          hashSet.add(people1);
  8.          hashSet.add(people2);
  9.          hashSet.add(people3);
  10.          hashSet.add(people4);
  11.          System.out.println(hashSet);
  12.          //输出:[People{name=’大大’, age=5}, People{name=’中中’, age=4}, People{name=’小小’, age=3}, People{name=’中中’, age=4}]
  13. }

很明显,我重写equals方法,那么people2和people3的equals应该相同,所以不能放入HashSet,但它们的hashCode方法返回不同,所以导致同样能放入HashSet

重点:对于Set集合必须要同时重写这两个方法,要不然Set的特性就被破坏了

到此这篇关于Java的CollectionUtils工具类详解的文章就介绍到这了,更多相关Java CollectionUtils内容请搜索我们以前的文章或继续浏览下面的相关文章希望大家以后多多支持我们!

标签

发表评论