Collections增加了更多实用的集合,是java.util.Collections的扩展。
官方网站:http://commons.apache.org/proper/commons-collections/index.html
常用的容器
Map
对等Map——BidiMap
可通过key找到value,亦可通过value找到key
BidiMap bidi = new TreeBidiMap();
bidi.put("SIX", "6");
bidi.get("SIX"); // returns "6"
bidi.getKey("6"); // returns "SIX"
bidi.removeValue("6"); // removes the mapping
BidiMap inverse = bidi.inverseBidiMap(); // returns a map with keys and values swapped
注意,getKey方法,对于存在有相同value的情况,只会返回最后放入map的key
BidiMap bidi = new TreeBidiMap();
bidi.put("a", 1);
bidi.put("b", 1);
bidi.put("c", 2);
String key = (String) bidi.getKey(1);
System.out.print(key);
上面代码返回c
有序Map——OrderedMap
接口为OrderedMap,有两种实现:LinkedMap、ListOrderedMap
OrderedMap map = new LinkedMap();
map.put("FIVE", "5");
map.put("SIX", "6");
map.put("SEVEN", "7");
map.firstKey(); // returns "FIVE"
map.nextKey("FIVE"); // returns "SIX"
map.nextKey("SIX"); // returns “SEVEN”
多值Map——MultiMap
用于将多个值映射到一个key上,此时get返回的就是一个集合
String key = "madmatrix";
MultiMap mhm = new MultiValueMap();
mhm.put(key, "A");
mhm.put(key, "B");
mhm.put(key, "C");
Collection<String> coll = (Collection) mhm.get(key);
Iterator<String> iter = coll.iterator();
while (iter.hasNext()) {
System.out.println(iter.next());
}
CaseInsensitiveMap
key不区分大小写的map
LRUMap
Least Recently Used Map。该map在初始化的时候大小固定,如果满了,再往里加东西,会先删除最近最少被使用的键值对。
put和get操作会改变键值对在map中的位置。而查询的方法如containsKey、containsValue以及通过iteration均不会改变kv的位置。
MultiKeyMap
按照字面意思理解即可,支持多个key映射到一个value。
private MultiKeyMap cache = MultiKeyMap.multiKeyMap(new LRUMap(50));
public String getAirlineName(String code, String locale) {
String name = (String) cache.get(code, locale);
if (name == null) {
name = getAirlineNameFromDB(code, locale);
cache.put(code, locale, name);
}
return name;
}
Bag
bag的使用场景是:存储多个集合的拷贝,并在需要的时候获取拷贝个数。
HashBag是Bag接口的一个标准实现。而BagUtils提供一组static的方法让调用者获取经过不同装饰后的Bag实例。
Bag bag = new HashBag();
bag.add("ONE", 6); // add 6 copies of "ONE"
bag.remove("ONE", 2); // removes 2 copies of "ONE"
bag.getCount("ONE"); // returns 4, the number of copies in the bag (6 - 2)
Iterator<String> iter = bag.iterator ();
while (iter.hasNext()) {
System.out.println(iter.next());
}
输出4个ONE字符串
辅助
Map迭代器——MapIterator
替代使用Set和EntrySet遍历map的方式
IterableMap map = new HashedMap();
MapIterator it = map.mapIterator();
while (it.hasNext()) {
Object key = it.next();
Object value = it.getValue();
it.setValue(newValue);
}
参考
《Jakarta Commons笔记》Commons Collections
《Apache Commons - Collections》