我正在尝试通过streams
和Lambdas
将JSONArray
转换为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"));