依赖
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-collections4</artifactId>
<version>4.1</version>
</dependency>
CollectionUtils
List<String> names = new ArrayList<String>(){{
add("a");
add("b");
}};
String[] arr = {"c","d"};
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