How to use, Apache commons collections from jython.
Apache commons collections is an extension of java.util.Collections and has the following benefits over the default Collections from Java.
Apache collections package contains
1]Bags
2]Maps
Ordered Maps
Bidirectional Maps [BidiMaps]
MapIterators
3]Buffers and Queues
An usage example of MapIterator and BidiMaps is given below.
CODE:
from org.apache.commons.collections.bidimap import DualHashBidiMap
map = DualHashBidiMap()
map.put("A", "1")
map.put("B", "2")
map.put("C", "3")
print "### Accessing Map using values"
# Access the same map using keys.
print "Key for value 2 :", map.getKey("2")
print "Key for value 3 :", map.getKey("3")
print "Key for value 3 :", map.getKey("1")
print "\n\n### Accessing Map using keys"
# Access the same map using values.
print "Value for key B :", map.get("B")
print "Value for Key C :", map.getKey("C")
print "Value for Key A :", map.getKey("A")
OUTPUT:
### Accessing Map using values
Key for value 2 : B
Key for value 3 : C
Key for value 3 : A
### Accessing Map using keys
Value for key B : 2
Value for Key C : None
Value for Key A : None
### Iterator Usage :
A 1
C 3
B 2
Monday, April 26, 2010
Tuesday, April 20, 2010
Java Object serialization
Here i have used Java's object serialization to serialize a map into memory and create that map back from memory. This is helpful if your are trying to dump objects into databases [into blob cloumns] instead of Files.
Normal googling gives serialization of objects into Files.
from java.io import ObjectOutputStream, ObjectInputStream, ByteArrayOutputStream, ByteArrayInputStream
//JYTHON CODE USING JAVA OBJECT SERIALIZATION
from java.util import HashMap
m = HashMap()
m.put("Name", "Sarath")
m.put("Company", "Strand")
print m
bout = ByteArrayOutputStream()
oout = ObjectOutputStream(bout)
oout.writeObject(m)
bytes = bout.toByteArray()
bin = ByteArrayInputStream(bytes)
#bin.write(bytes, 0, bytes.length)
oin = ObjectInputStream(bin)
print "### output"
m2 = oin.readObject()
print m2
Normal googling gives serialization of objects into Files.
from java.io import ObjectOutputStream, ObjectInputStream, ByteArrayOutputStream, ByteArrayInputStream
//JYTHON CODE USING JAVA OBJECT SERIALIZATION
from java.util import HashMap
m = HashMap()
m.put("Name", "Sarath")
m.put("Company", "Strand")
print m
bout = ByteArrayOutputStream()
oout = ObjectOutputStream(bout)
oout.writeObject(m)
bytes = bout.toByteArray()
bin = ByteArrayInputStream(bytes)
#bin.write(bytes, 0, bytes.length)
oin = ObjectInputStream(bin)
print "### output"
m2 = oin.readObject()
print m2
Labels:
java object serilaization jython
Subscribe to:
Comments (Atom)