python调用Java方法传入HashMap ArrayList
1、Java代码:
package com;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
public class ListTest {
public ListTest(){}
public ArrayList<Double> sumList(ArrayList<Double> arrayList){
double sum = 0.0;
for (Double num :arrayList){
sum += num;
}
ArrayList<Double> doubles = new ArrayList<Double>();
doubles.add(sum);
return doubles;
}
public HashMap<String,Integer> countWrod(String str){
String[] st = str.split(" ");
HashMap<String,Integer> map = new HashMap<>();
for (String strs:st){
if (map.containsKey(strs)){
map.put(strs,map.get(strs)+1);
}else{
map.put(strs,1);
}
}
return map;
}
public ArrayList<HashMap<String,Double>> listMap(ArrayList<HashMap<String,Double>> lm){
return new ArrayList<>(lm);
}
public static void main(String[] args){
ListTest t = new ListTest();
Double[] als = {1.0,2.0,3.0};
ArrayList s = t.sumList(new ArrayList<Double>(Arrays.asList(als)));
System.out.println(s);
ArrayList<HashMap<String,Double>> lt = new ArrayList<HashMap<String,Double>>();
HashMap<String,Double> md = new HashMap<>();
md.put("我的",25.);
lt.add(md);
System.out.println(t.listMap(lt));
String st = "wo is are you do wo is you get set add al al als al";
System.out.println(t.countWrod(st));
}
}
2、封装成jar包请看上一篇博文
https://www.cnblogs.com/wuzaipei/p/11161247.html
3、python代码
import time
from jpype import *
import os
import numpy as np
import json
if __name__ == '__main__':
jdkPath = r"D:\Java1.8\jdk1.8.0_191\jre\bin\server\jvm.dll"
# 注意一个重要的问题,导入包的时候路径不能有中文。
jarpath = os.path.join(os.path.abspath('.'), 'javaCode/listMapTest.jar')
print(jarpath)
startJVM(jdkPath,"-ea","-Djava.class.path=%s" % jarpath)
java.lang.System.out.println(" helloworld! ")
model = JClass('com.ListTest')
# 或者通过JPackage引用Test类
# javaIoStream = JPackage('javaIoStream')
# fibnq = javaIoStream.fibnq()
ListTest= model()
# 1、传入List
al = [1,2,3,4,2,5]
jl = java.util.ArrayList()
for i in al:
jl.add(float(i))
ll = ListTest.sumList(jl).toString()
# 2、接收Map
str = "life is short we use python list is shor we use java"
maps = ListTest.countWrod(str).toString()
# 3、传入 list 嵌套map。
lmst = [{"admin":float(2),"我不做大哥好多年":float(9.0)},{"我不做大哥好多年":float(9.0)},{"i love you":0.520}]
listMaps = java.util.ArrayList()
for item in lmst:
mp = java.util.HashMap()
for k in item.keys():
mp.put(k,item.get(k))
listMaps.add(mp)
listM = ListTest.listMap(listMaps).toString()
shutdownJVM()
print(json.loads(ll)[0])
stmp = ""
for item in maps:
if item == "=":
stmp += ":"
else:
stmp += item
print(stmp)
print(listM)
自动化学习。

浙公网安备 33010602011771号