Java-8 JSONArray to HashMap

Pan*_*hal 5 java lambda json java-8 java-stream

我正在尝试转换JSONArrayMap<String,String>viastreamsLambdas. 以下不起作用:

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"));
Run Code Online (Sandbox Code Playgroud)

为了避免类型转换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)
Run Code Online (Sandbox Code Playgroud)

Line 4给出以下错误:

Type mismatch: cannot convert from Object to HashMap<String,String>
Run Code Online (Sandbox Code Playgroud)

我正在尝试学习 Lambdas 和流。有人可以帮我吗?

Sam*_*Sun 4

看起来 json-simpleJSONArray扩展了 anArrayList而不提供任何泛型类型。这会导致stream返回一个Stream也没有类型的值。

知道了这一点,我们就可以在 的接口上进行编程,List而不是JSONArray

List<Object> jsonarray = new JSONArray();
Run Code Online (Sandbox Code Playgroud)

这样做将使我们能够像这样正确地进行流式传输:

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