我正在尝试通过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和stream。有人能帮帮我吗?
发布于 2016-01-07 23:06:39
看起来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"));https://stackoverflow.com/questions/34657172
复制相似问题