首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Java-8 JSONArray到HashMap

Java-8 JSONArray到HashMap
EN

Stack Overflow用户
提问于 2016-01-07 22:06:55
回答 1查看 17.1K关注 0票数 5

我正在尝试通过streamsLambdasJSONArray转换为Map<String,String>。以下代码不起作用:

代码语言:javascript
复制
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给出以下错误:

代码语言:javascript
复制
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给出了以下错误:

代码语言:javascript
复制
Type mismatch: cannot convert from Object to HashMap<String,String>

我正在尝试学习Lambdas和stream。有人能帮帮我吗?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2016-01-07 23:06:39

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

了解了这一点,我们就可以在List的界面上而不是在JSONArray上编程

代码语言:javascript
复制
List<Object> jsonarray = new JSONArray();

这样做可以让我们像这样正确地流媒体:

代码语言:javascript
复制
Map<String, String> map = jsonarray.stream().map(Object::toString).collect(Collectors.toMap(s -> s, s -> "value"));
票数 4
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/34657172

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档