5

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.

2 Answers2

1

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'>
Remis Haroon - رامز
  • 3,304
  • 4
  • 34
  • 62
0

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

int 

return an

ArrayList<String>
Corie LeClair
  • 51
  • 1
  • 9