Java 8: How to write lambda stream to work with JsonArray?

JSONArray is a sub-class of java.util.ArrayList and JSONObject is a sub-class of java.util.HashMap.

Therefore, new JSONObject().put("name", "John") returns the previous value associated with the key (null), not the JSONObject instance. As a result, null is added to the JSONArray.

This, on the other hand, works:

    JSONArray jsonArray = new JSONArray();
    JSONObject j1 = new JSONObject();
    j1.put ("name", "John");
    JSONObject j2 = new JSONObject();
    j2.put ("name", "David");
    jsonArray.add(j1);
    jsonArray.add(j2);
    Stream<String> ss = jsonArray.stream().map (json->json.toString ());
    List<String> list = ss.collect (Collectors.toList ());
    System.out.println(list);

For some reason I had to split the stream pipeline into two steps, because otherwise the compiler doesn't recognize that .collect (Collectors.toList()) returns a List.

The output is:

[{"name":"John"}, {"name":"David"}]

Try with IntStream.

List<String> jsonObject = IntStream
       .range(0,jsonArray.size())
       .mapToObj(i -> jsonArray.getJSONObject(i))
       .collect(Collectors.toList());