2016-01-07 200 views
4

我试图通过streamsLambdasJSONArray转换为Map<String,String>。以下是不工作:Java-8 JSONArray到HashMap

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> 

我在努力学习兰姆达斯和溪流。有人可以帮我吗?

+1

我不认为这是必然一个副本。这是转换JSONArray,并且问题产生于使用lambda表达式 –

+0

@ozOli在您认为错误的东西downvote或作出反应之前进行两次READ/THINK两次 –

回答

3

看来,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")); 
+0

该分配生成编译器警告。它应该是'List ',而不是'List '。 – VGR

+0

@VGR它不会产生任何警告。我刚刚尝试过。 –

+0

它根据您的设置生成警告。但是,它也会在'.add'上产生一个警告,所以我没有想太多。 –