Java-8 JSONArray 到 HashMap
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/34657172/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Java-8 JSONArray to HashMap
提问by Pankaj Singhal
I'm trying to convert JSONArray
to a Map<String,String>
via streams
and Lambdas
. The following isn't working:
我正在尝试转换JSONArray
为Map<String,String>
viastreams
和Lambdas
. 以下不起作用:
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"));
To Avoid typecasting in Line 4
, I'm doing Line 3
为了避免在 中Line 4
进行类型转换,我正在做Line 3
Line 3
gives the following errors:
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)
And Line 4
gives the following error:
并Line 4
给出以下错误:
Type mismatch: cannot convert from Object to HashMap<String,String>
I'm trying to learn Lambdas and streams. Can somebody help me out?
我正在尝试学习 Lambdas 和流。有人可以帮我吗?
采纳答案by Sam Sun
It would appear that json-simple's JSONArray
extends an ArrayList
without providing any generic types. This causes stream
to return a Stream
that doesn't have a type either.
看起来 json-simple 的JSONArray
扩展ArrayList
没有提供任何泛型类型。这会导致stream
返回一个Stream
也没有类型的。
Knowing this, we can program on the interface of List
instead of JSONArray
知道了这一点,我们可以在接口上编程List
而不是JSONArray
List<Object> jsonarray = new JSONArray();
Doing this will allow us to stream properly like so:
这样做将使我们能够像这样正确地流式传输:
Map<String, String> map = jsonarray.stream().map(Object::toString).collect(Collectors.toMap(s -> s, s -> "value"));