Showing posts with label collections. Show all posts
Showing posts with label collections. Show all posts

Thursday, May 29, 2014

Persistent (Immutable) Collections

@Grapes(
    @Grab(group='org.pcollections', module='pcollections', version='2.1.2')
)
import org.pcollections.*

PSet set = HashTreePSet.empty()
set = set + "something"
println set
println(set + "something else")
println set // immutable

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
}

Trove - high speed regular and primitive collections

/*
 * see: http://trove.starlight-systems.com/
 */
@Grapes(
    @Grab(group='net.sf.trove4j', module='trove4j', version='3.0.2')
)
import gnu.trove.set.*
import gnu.trove.set.hash.*
import gnu.trove.list.*
import gnu.trove.list.array.*
import gnu.trove.list.linked.*
import gnu.trove.map.*
import gnu.trove.map.hash.*

//Most Trove classes start with the letter "T" to indicate that they're part of the Trove library.
THashSet s = new THashSet()
100.times { i ->
  s.add ((i / 2).toInteger())
}
assert s.size() == 50
assert s.contains(0)

TIntArrayList a = new TIntArrayList()
100.times { i ->
  a.add ((i / 3).toInteger())
}
assert a.size() == 100
assert a.get(0) == 0

TIntLinkedList l = new TLinkedList()
100.times { i ->
  l.add ((i / 4).toInteger())
}
assert l.size() == 100
assert l.get(0) == 0

THashMap m = new THashMap()
m['a'] = 1
m.b = 2
assert m.a == 1