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'>