Commons Collections增强了Java Collections Framework。 它提供了几个功能,使收集处理变得容易。 它提供了许多新的接口,实现和实用程序。 Commons Collections的主要功能如下
Bag - Bag界面简化了每个对象具有多个副本的集合。
BidiMap - BidiMap接口提供双向映射,可用于使用值使用键或键查找值。
MapIterator - MapIterator接口提供简单而容易的迭代迭代。
Transforming Decorators - 转换装饰器可以在将集合添加到集合时更改集合的每个对象。
Composite Collections - 在需要统一处理多个集合的情况下使用复合集合。
Ordered Map - 有序地图保留添加元素的顺序。
Ordered Set - 有序集保留了添加元素的顺序。
Reference map - 参考图允许在密切控制下对键/值进行垃圾收集。
Comparator implementations - 可以使用许多Comparator实现。
Iterator implementations - 许多Iterator实现都可用。
Adapter Classes - 适配器类可用于将数组和枚举转换为集合。
Utilities - 实用程序可用于测试测试或创建集合的典型集合论属性,例如union,intersection。 支持关闭。
Commons Collections - Bag
Bag定义了一个集合,用于计算对象在集合中出现的次数。 例如,如果Bag包含{a,a,b,c},则getCount(“a”)将返回2,而uniqueSet()将返回唯一值。
import org.apache.commons.collections4.Bag;
import org.apache.commons.collections4.bag.HashBag;
public class BagTester {
public static void main(String[] args) {
Bag<String> bag = new HashBag<>();
//add "a" two times to the bag.
bag.add("a" , 2);
//add "b" one time to the bag.
bag.add("b");
//add "c" one time to the bag.
bag.add("c");
//add "d" three times to the bag.
bag.add("d",3);
//get the count of "d" present in bag.
System.out.println("d is present " + bag.getCount("d") + " times.");
System.out.println("bag: " +bag);
//get the set of unique values from the bag
System.out.println("Unique Set: " +bag.uniqueSet());
//remove 2 occurrences of "d" from the bag
bag.remove("d",2);
System.out.println("2 occurences of d removed from bag: " +bag);
System.out.println("d is present " + bag.getCount("d") + " times.");
System.out.println("bag: " +bag);
System.out.println("Unique Set: " +bag.uniqueSet());
}
}
它将打印以下结果:
d is present 3 times.
bag: [2:a,1:b,1:c,3:d]
Unique Set: [a, b, c, d]
2 occurences of d removed from bag: [2:a,1:b,1:c,1:d]
d is present 1 times. bag: [2:a,1:b,1:c,1:d] Unique Set: [a, b, c, d]
Commons Collections - BidiMap
使用双向映射,可以使用值查找键,并且可以使用键轻松查找值。
import org.apache.commons.collections4.BidiMap;
import org.apache.commons.collections4.bidimap.TreeBidiMap;
public class BidiMapTester {
public static void main(String[] args) {
BidiMap<String, String> bidi = new TreeBidiMap<>();
bidi.put("One", "1");
bidi.put("Two", "2");
bidi.put("Three", "3")<