You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何通过Py4j将Java List转换为Python列表?

Converting a JavaList from Py4J Java Gateway to Python Native Types

Great question! I’ve run into this exact situation when working with Py4J, and even though the docs focus more on Python-to-Java conversions, the reverse is actually straightforward once you know the trick.

Quick One-Liner Conversion

Py4J’s JavaList implements Python’s iterator interface under the hood, so you can directly convert it to a Python list using the built-in list() function. Here’s a concrete example:

from py4j.java_gateway import JavaGateway

# Initialize the gateway and get a JavaList instance
gateway = JavaGateway()
java_list = gateway.jvm.java.util.Arrays.asList("apple", "banana", "cherry")

# Convert to Python list in one step
python_list = list(java_list)

print(type(python_list))  # Output: <class 'list'>
print(python_list)        # Output: ['apple', 'banana', 'cherry']

Handling Nested Java Collections

If you’re dealing with nested structures (like a JavaList containing other JavaLists or JavaMaps), you can write a simple recursive function to convert everything to Python native types. Py4J automatically converts basic Java types (like String, Integer, Boolean) to their Python equivalents, so you just need to handle collections:

def java_to_python(java_obj):
    # Check if it's an iterable Java collection (List, Set, etc.)
    if hasattr(java_obj, "__iter__"):
        return [java_to_python(item) for item in java_obj]
    # Handle Java Maps by converting to Python dictionaries
    elif hasattr(java_obj, "entrySet"):
        return {entry.getKey(): java_to_python(entry.getValue()) for entry in java_obj.entrySet()}
    # For basic types, return directly (Py4J handles conversion)
    else:
        return java_obj

# Test with a nested JavaList
nested_java_list = gateway.jvm.java.util.ArrayList()
nested_java_list.add(gateway.jvm.java.util.Arrays.asList(10, 20, 30))
nested_java_list.add(gateway.jvm.java.util.Arrays.asList(40, 50, 60))

python_nested = java_to_python(nested_java_list)
print(python_nested)  # Output: [[10, 20, 30], [40, 50, 60]]

A Quick Note on Type Conversion

Py4J does automatic conversion for most primitive and common Java types:

  • Java String → Python str
  • Java Integer/Long → Python int
  • Java Boolean → Python bool
  • Java Double → Python float

So when you convert a JavaList, all its elements will already be in Python-native types without extra work.

内容的提问来源于stack exchange,提问作者Marcel_marcel1991

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.27 09:21:41