Skillversitas

Using Java Collection Types

Java's collection framework (List, Set, Map and their implementations) is available in Jython, and Jython bridges the two worlds: Java collections support Python-style iteration and len(), and Python lists/dicts can be passed to Java APIs that expect collections.

ArrayList (List)

import java.util

al = java.util.ArrayList()
al.add("apple")
al.add("banana")
al.add(0, "zero")           # insert at index
print(al.get(0))            # zero
print(al.size())            # 3
print(len(al))              # 3 - len works on java.util collections

for item in al:             # direct iteration
    print(item)

al.remove("banana")
print(al)                   # [zero, apple]
java.util.Collections.sort(al)

HashMap (Map)

from java.util import HashMap

mp = HashMap()
mp.put("name", "Skillversitas")
mp.put("year", 2026)
print(mp.get("name"))
print(mp.containsKey("year"))
print(mp.keySet())

for key in mp.keySet():
    print(key, mp.get(key))

HashSet (Set)

from java.util import HashSet

hs = HashSet()
hs.add(1)
hs.add(2)
hs.add(1)          # duplicate ignored
print(hs.size())   # 2
print(hs.contains(2))

Python-Java Collection Interop

import java.util

# Python list -> Java ArrayList
py_list = [1, 2, 3]
al = java.util.ArrayList(py_list)
print(al)

# Java List -> Python list
back = list(al)
print(back, type(back))

# Python dict -> Java Map
mp = java.util.HashMap({"a": 1, "b": 2})
print(mp.get("a"))

When to Use Which Collection

  • Use Python list/dict/set for internal logic - they are faster for pure-Python code paths.
  • Use Java collections when you must hand data to a Java API, or when a Java method returns one and you want to keep it.
  • Convert at the boundary (list(java_list), ArrayList(py_list)) rather than mixing in hot loops.

Summary

Java collections work in Jython with Python ergonomics: ArrayList, HashMap, and HashSet support add/get/put/contains plus Python iteration and len(). Convert across the boundary with list() and the collection constructors, prefer Python containers for internal logic, and reach for Java collections at Java API boundaries.