Friday, February 10, 2012

Apache Commons Collections

@Grapes(
    @Grab(group='commons-collections', module='commons-collections', version='3.2.1')
)
import org.apache.commons.collections.*
import org.apache.commons.collections.map.*
import org.apache.commons.collections.bidimap.*

IterableMap map1 = [a:1, b:2] as HashedMap
map1.each {
    print it.key
    println it.value
}

OrderedMap map = new LinkedMap()
map.with {
    put("FIVE", "5")
    put("SIX", "6")
    put("SEVEN", "7")
    assert firstKey() == "FIVE"
    assert nextKey("FIVE") == "SIX" 
    assert nextKey("SIX")  == "SEVEN"
}

BidiMap bidi = new TreeBidiMap()
bidi.with {
    put("SIX", "6")
    assert get("SIX") == "6"
    assert get("SIX") == "6"
    assert getKey("6") == "SIX"
    removeValue("6")
    assert getKey("SIX") == null
    put("ONE", "1")
}
BidiMap inverse = bidi.inverseBidiMap()  // returns a map with keys and values swapped
assert inverse.getKey("ONE") == "1"

Buffer buffer = new UnboundedFifoBuffer()
buffer.with {
    add("ONE")
    add("TWO")
    add("THREE")
    assert remove() == "ONE"
    assert remove() == "TWO"
}

Bag bag = new HashBag()
bag.with {
    add("ONE", 6)  // add 6 copies of "ONE"
    remove("ONE", 2)  // removes 2 copies of "ONE"
    assert getCount("ONE") == 4
}

No comments:

Post a Comment