这里提到的解决方案虽然可行,但它们会在流上下文之外改变对象,应该避免这种情况。
因此,不要使用返回void
的终止操作.forEach()
。正确的方法是使用.map()
,正如其名称所示,将一个值映射到另一个值。在您的情况下,您想要执行的第一个操作是将Person映射为JSONObject。第二个操作是一个reducer函数,您想要将所有的JSONObject减少为一个JSONArray对象。
public JSONArray mapListToJsonArray(List<Person> persons) {
List<JSONObject> jsonObjects = persons
.stream()
.map(person -> {
JSONObject json = new JSONObject();
json.put("firstName", person.getFirstName());
json.put("lastName", person.getLastName());
return json;
})
.collect(Collectors.toList());
return new JSONArray(jsonObjects);
}
不幸的是,json.org实现的JSONArray没有一种容易合并两个数组的方法。所以我没有将其减少到JSONArray,而是首先将所有JSONObjects收集为列表,然后从列表创建了一个JSONArray。
如果用方法引用代替lambda表达式,解决方案看起来会更好。
public JSONArray mapListToJsonArray(List<Person> persons) {
List<JSONObject> jsonObjects = persons
.stream()
.map(this::mapPersonToJsonObject)
.collect(Collectors.toList());
return new JSONArray(jsonObjects);
}
public JSONObject mapPersonToJsonObject(Person person) {
JSONObject json = new JSONObject();
json.put("firstName", person.getFirstName());
json.put("lastName", person.getLastName());
return json;
}