Java-8 JSONArray to HashMap



我正在尝试通过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"));

为了避免在Line 4中进行类型转换,我正在进行Line 3

Line 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)

Line 4给出以下错误:

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

我正在努力学习Lambdas和streams。有人能帮我吗?

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"));

最新更新