I'm very new to Java 8 lambdas and stuff... I want to write a lambda function that takes a JsonArray, goes over its JsonObjects and creates a list of values of certain field.
For example, a function that takes the JsonArray: [{name: "John"}, {name: "David"}] and returns a list of ["John", "David"].
I wrote the following code:
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
public class Main {
public static void main(String[] args) {
JSONArray jsonArray = new JSONArray();
jsonArray.add(new JSONObject().put("name", "John"));
jsonArray.add(new JSONObject().put("name", "David"));
List list = (List) jsonArray.stream().map(json -> json.toString()).collect(Collectors.toList());
System.out.println(list);
}
}
However, I get an error:
Exception in thread "main" java.lang.NullPointerException
DO you know how to resolve it?
Yes, I recognized that result of put is being added to json array instead of json object. Should be like this.
and output is now [{"name":"John"}, {"name":"David"}] like expected
JSONArray is a sub-class of
java.util.ArrayList
and JSONObject is a sub-class ofjava.util.HashMap
.Therefore,
new JSONObject().put("name", "John")
returns the previous value associated with the key (null
), not theJSONObject
instance. As a result,null
is added to theJSONArray
.This, on the other hand, works:
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 aList
.The output is:
Try with IntStream.