Java-8 JSONArray转换为HashMap

6

我正在尝试通过streamsLambdasJSONArray转换为Map<String,String>。以下代码不起作用:

org.json.simple.JSONArray jsonArray = new org.json.simple.JSONArray();
jsonArray.add("pankaj");
HashMap<String, String> stringMap = jsonArray.stream().collect(HashMap<String, String>::new, (map,membermsisdn) -> map.put((String)membermsisdn,"Error"), HashMap<String, String>::putAll);
HashMap<String, String> stringMap1 = jsonArray.stream().collect(Collectors.toMap(member -> member, member -> "Error"));

为避免在第4行出现类型转换错误,我正在执行第3行第3行会产生以下错误:
Multiple markers at this line
- The type HashMap<String,String> does not define putAll(Object, Object) that is applicable here
- The method put(String, String) is undefined for the type Object
- The method collect(Supplier, BiConsumer, BiConsumer) in the type Stream is not applicable for the arguments (HashMap<String, String>::new, (<no type> map, <no type> membermsisdn) 
 -> {}, HashMap<String, String>::putAll)

第四行会出现以下错误:

Type mismatch: cannot convert from Object to HashMap<String,String>

我正在尝试学习Lambda表达式和流。有人可以帮助我吗?


1
我不认为这一定是一个重复的问题。这是转换JSONArray的问题,问题出在使用lambda表达式上。 - samczsun
@ozOli 在你对某些你认为是错误的事情进行投票或反应之前,请三思而后行。 - Pankaj Singhal
1个回答

4
似乎json-simple的JSONArray继承了ArrayList,但没有提供任何泛型。这会导致stream返回一个没有类型的Stream
了解这一点后,我们可以在List的接口上进行编程,而不是JSONArray的接口。
List<Object> jsonarray = new JSONArray();

这样做将使我们能够正常流式传输,如下所示:

Map<String, String> map = jsonarray.stream().map(Object::toString).collect(Collectors.toMap(s -> s, s -> "value"));

1
该赋值语句会产生编译器警告。应该使用 List<?> 而不是 List<Object> - VGR
1
@VGR,它不会生成任何警告。我刚试过了。 - Pankaj Singhal
@SamSun,添加.map(Object::toString)会调用Object类或JSONArray类的toString方法?我猜测是JSONArray的,对吗? - Pankaj Singhal
1
它在JSONArray的每个元素上调用toString - samczsun
1
JSONArray 的 toString 方法将被调用。 - samczsun
显示剩余2条评论

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接