6

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?

2
  • 1
    I don't think this is necessarily a duplicate. This is converting a JSONArray, and the problem arises from the use of lambdas Commented Jan 7, 2016 at 14:19
  • @ozOli READ/THINK twice before you downvote or reacting on something you think is wrong Commented Jan 7, 2016 at 14:23

1 Answer 1

4

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"));
Sign up to request clarification or add additional context in comments.

7 Comments

That assignment generates a compiler warning. It should be List<?>, not List<Object>.
@VGR It doesn't generate any warning. I just tried.
It generates a warning depending on your settings. However, it would also generate a warning on .add so I didn't think too much of it.
It calls toString on each element of the JSONArray
JSONArray's toString will be called
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.