Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java-8 JSONArray to HashMap

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

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 3 gives the following errors:

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:

Type mismatch: cannot convert from Object to HashMap<String,String>

I'm trying to learn Lambdas and streams. Can somebody help me out?

like image 464
Pankaj Singhal Avatar asked Sep 25 '22 17:09

Pankaj Singhal


1 Answers

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.

Knowing this, we can program on the interface of List instead of 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"));
like image 113
Sam Sun Avatar answered Oct 19 '22 08:10

Sam Sun