Collectives™ on Stack Overflow
Find centralized, trusted content and collaborate around the technologies you use most.
Learn more about Collectives
Teams
Q&A for work
Connect and share knowledge within a single location that is structured and easy to search.
Learn more about Teams
I am wondering if it is possible, and if yes how, to convert a JavaList that is received via the Java Gateway in Python to a python list. Or something similar that is a native python type.
In the docs of py4j all I can see is converting python types to java but not vice versa.
As it is mentioned in the official documentation under the
advanced topics
section
, Java collections of type Array, List, Set, Map, Iterator are automatically converted to compatible formats in the calling Python code.
It is to be noted that java list is not converted to a pure Python list, but into a
py4j.java_collections.JavaList
.
Let's see an example which demonstrates this:
JAVA Code:
public class Py4JEntryPoint {
private List<String> javaList = new ArrayList<>();
public Py4JEntryPoint(){
javaList.add("Hello");
javaList.add("How");
javaList.add("you");
javaList.add("doin...!!!");
public List<String> getJavaList(){
return javaList;
public static void main(String[] args) {
GatewayServer gatewayServer = new GatewayServer(new Py4JEntryPoint());
gatewayServer.start();
System.out.println("Gateway Server Started");
Python Code, calling the Gateway:
gateway = JavaGateway()
jList = gateway.entry_point.getJavaList()
print(jList)
#output: ['Hello', 'How', 'you', 'doin...!!!']
print("Type of list returned by Java Gateway", type(jList)) #
#output: Type of list returned by Java Gateway <class 'py4j.java_collections.JavaList'>
pyList = list(jList)
print(pyList)
#output: ['Hello', 'How', 'you', 'doin...!!!']
print("Type of list after conversion", type(pyList))
#output: Type of list after conversion <class 'list'>
As far as I know, PY4J will convert them automatically, ArrayList to list in python.
https://www.py4j.org/
Use the first example which includes the addition method, but instead of it returning the an
return an
ArrayList<String>
Thanks for contributing an answer to Stack Overflow!
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
To learn more, see our tips on writing great answers.