依赖

  1. <dependency>
  2. <groupId>org.apache.commons</groupId>
  3. <artifactId>commons-collections4</artifactId>
  4. <version>4.1</version>
  5. </dependency>

image.png

CollectionUtils

  1. List<String> names = new ArrayList<String>(){{
  2. add("a");
  3. add("b");
  4. }};
  5. String[] arr = {"c","d"};
  6. CollectionUtils.addAll(names,arr);//[a, b, c, d]
List<String> collect = (List<String>) CollectionUtils.collect(names, name -> name + "*");
//[a*, b*, c*, d*]

ListUtils

MapUtils

SetUtils

Bag

HashBag

public void test()
   {
      HashBag hashBag = new HashBag();
      String s1 = "s1";
      String s2 = "s2";
      hashBag.add(s1);
      hashBag.add(s1);
      hashBag.add(s2, 3);
      // 获得包中元素迭代器
      Iterator<?> iterator = hashBag.iterator();
      System.out.println("包中元素为:");
      while (iterator.hasNext())
      {
         System.out.println(iterator.next());
      }
      System.out.println("包中元素个数为:" + hashBag.size());
      System.out.println("包中entity1个数为:" + hashBag.getCount(s1));
      System.out.println("去重后个数为:" + hashBag.uniqueSet().size());
   }

包中元素为:
s1
s1
s2
s2
s2
包中元素个数为:5
包中entity1个数为:2
去重后个数为:2

Tree Bag

TreeBag使用TreeMap作为数据存储,用法与HashBag类似,只是TreeBag会使用自然顺序对元素进行排序。

@Test
   public void test()
   {
      TreeBag hashBag = new TreeBag();
      String s1 = "s1";
      String s2 = "s2";
      String s3 = "s3";
      hashBag.add(s3);
      hashBag.add(s1);
      hashBag.add(s2);
      // 获得包中元素迭代器
      Iterator<?> iterator = hashBag.iterator();
      System.out.println("包中元素为:");
      while (iterator.hasNext())
      {
         System.out.println(iterator.next());
      }
      System.out.println("包中元素个数为:" + hashBag.size());
      System.out.println("包中entity1个数为:" + hashBag.getCount(s1));
      System.out.println("去重后个数为:" + hashBag.uniqueSet().size());
   }

包中元素为:
s1
s2
s3
包中元素个数为:3
包中entity1个数为:1
去重后个数为:3