test

Apache Commons Collections

Apache Commons Collections是一个用来处理集合Collection的开源工具包,比如你可以用来将一个对象拷贝多份并存放到一个Bag对象中(这个看来没有多大用处),得到两个集合里相同的元素,删除一个集合里的元素并返回删除的元素,还有除了通过一个集合里的key得到value外,还可以通过value得到key,也就是说这个集合里的value是唯一的,另外还可以将一个集合里的key和value值对调,得到一个集合里的某一key之后的另一个key值等等。
官方网址是:http://commons.apache.org/collections/

/**

* 通过Iterator遍历得到一个map里的key和value

*/

private static void testHashedMap(){

IterableMap map = new HashedMap();

map.put("a","1");

map.put("b",new Integer(2));

MapIterator it = map.mapIterator();

while (it.hasNext()) {

Object key = it.next();

Object value = it.getValue();

System.out.println(">>key>>"+key+">>value>>"+value);

}

}

 

/**

* 得到集合里按顺序存放的key之后的某一Key

*/

private static void testLinkedMap(){

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"

System.out.println(map.firstKey()+">>"+map.nextKey("FIVE")+">>"+map.nextKey("SIX"));

}

 

/**

* 通过key得到value

* 通过value得到key

* 将map里的key和value对调

*/

private static void testTreeBidiMap(){

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

System.out.println(inverse);

}

 

/**

* 移除集合某一元素并返回移除的元素

*/

private static void testUnboundedFifoBuffer(){

Buffer buffer = new UnboundedFifoBuffer();

buffer.add("ONE");

buffer.add("TWO");

buffer.add("THREE");

System.out.println(buffer.remove()); // removes and returns the next in order, "ONE" as this is a FIFO

System.out.println(buffer.remove()); // removes and returns the next in order, "TWO" as this is a FIFO

System.out.println(buffer);

}

 

/**

* 得到两个集合中相同的元素

*/

private static void testCollectionUtilsRetainAll(){

List<String> list1 = new ArrayList<String>();

list1.add("1");

list1.add("2");

list1.add("3");

 

List<String> list2 = new ArrayList<String>();

list2.add("2");

list2.add("3");

list2.add("5");

Collection c = CollectionUtils.retainAll(list1, list2);

System.out.println(c);

}

 

/**

* 复制多个对象保存到Bag对象中

*/

private static void testHashBag(){

Bag bag = new HashBag();

bag.add("ONE", 6); // add 6 copies of "ONE"

bag.remove("ONE", 2); // removes 2 copies of "ONE"

System.out.println(bag.getCount("ONE")); // returns 4, the number of copies in the bag (6 - 2)

for (Iterator ite = bag.iterator();ite.hasNext();){

System.out.println(ite.next());

}

}

 

/**

* @param args

*/

public static void main(String[] args) {

// testLinkedMap();

// testTreeBidiMap();

testUnboundedFifoBuffer();

// testHashBag();

// testCollectionUtilsRetainAll();

}

posted @ 2020-06-15 11:41  西南大学张老师  阅读(305)  评论(0编辑  收藏  举报
test