我对 Java 8 lambda 和其他东西很陌生...我想编写一个 lambda 函数,它接受一个 JSONArray
,遍历它的 JSONObject
并创建特定字段的值列表。
例如,一个接受 JSONArray
的函数:[{name: "John"}, {name: "David"}]
并返回 [“约翰”、“大卫”]
。
我写了下面的代码:
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);
}
}
但是,我得到一个错误:
Exception in thread "main" java.lang.NullPointerException
你知道怎么解决吗?
最佳答案
尝试使用 IntStream。
List<String> jsonObject = IntStream
.range(0,jsonArray.size())
.mapToObj(i -> jsonArray.getJSONObject(i))
.collect(Collectors.toList());
关于Java 8 : How to write lambda stream to work with JsonArray?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44595433/