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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-02 23:10:08  来源:igfitidea点击:

Java-8 JSONArray to HashMap

javajsonlambdajava-8java-stream

提问by Pankaj Singhal

I'm trying to convert JSONArrayto a Map<String,String>via streamsand Lambdas. The following isn't working:

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

To Avoid typecasting in Line 4, I'm doing Line 3

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

Line 3gives 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 4gives 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 JSONArrayextends an ArrayListwithout providing any generic types. This causes streamto return a Streamthat doesn't have a type either.

看起来 json-simple 的JSONArray扩展ArrayList没有提供任何泛型类型。这会导致stream返回一个Stream也没有类型的。

Knowing this, we can program on the interface of Listinstead 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"));