Java 8: How to write lambda stream to work with JsonArray?(Java 8:如何编写 lambda 流以使用 JsonArray?)
问题描述
I'm very new to Java 8 lambdas and stuff... I want to write a lambda function that takes a JSONArray
, goes over its JSONObject
s 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?
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"}]
这篇关于Java 8:如何编写 lambda 流以使用 JsonArray?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:Java 8:如何编写 lambda 流以使用 JsonArray?


- Jersey REST 客户端:发布多部分数据 2022-01-01
- Spring Boot连接到使用仲裁器运行的MongoDB副本集 2022-01-01
- Safepoint+stats 日志,输出 JDK12 中没有 vmop 操作 2022-01-01
- C++ 和 Java 进程之间的共享内存 2022-01-01
- Eclipse 插件更新错误日志在哪里? 2022-01-01
- 将log4j 1.2配置转换为log4j 2配置 2022-01-01
- 从 finally 块返回时 Java 的奇怪行为 2022-01-01
- 如何使用WebFilter实现授权头检查 2022-01-01
- value & 是什么意思?0xff 在 Java 中做什么? 2022-01-01
- Java包名称中单词分隔符的约定是什么? 2022-01-01