您的位置:首页 > 运维架构 > Apache

Apache的commons组件的Map、Bag、Buffer等一些新奇的用法

2013-09-24 15:19 274 查看
1

package com.commons.components.collection;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;

import org.apache.commons.collections.Bag;
import org.apache.commons.collections.Buffer;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.collections.IterableMap;
import org.apache.commons.collections.MapIterator;
import org.apache.commons.collections.OrderedMap;
import org.apache.commons.collections.bag.HashBag;
import org.apache.commons.collections.buffer.UnboundedFifoBuffer;
import org.apache.commons.collections.map.HashedMap;
import org.apache.commons.collections.map.LinkedMap;

/**
* 测试包下的主要类
*
* @author chaigw
*
*/
public class MapTest {

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);
}
}

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"));
}

private static void testUnboundedFifoBuffer() {
Buffer buffer = new UnboundedFifoBuffer();
buffer.add("ONE");
buffer.add("TWO");
buffer.add("THREE");
System.out.println(buffer);
System.out.println(buffer.remove()); // removes and returns the next in
System.out.println(buffer.remove()); // removes and returns the next in
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);
}

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());
}
}

public static void main(String[] args) {
testHashedMap();
testLinkedMap();
testUnboundedFifoBuffer();
testCollectionUtilsRetainAll();
testHashBag();
}

}


2

>>key>>a>>value>>1
>>key>>b>>value>>2
FIVE>>SIX>>SEVEN
[ONE, TWO, THREE]
ONE
TWO
[THREE]
[2, 3]
4
ONE
ONE
ONE
ONE
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: