我有一个双数组,我需要使用 java streams
将数组转换为 JSONArray
。我尝试使用导致数据丢失的 forEach(共享可变性)。
public static JSONArray arrayToJson(double[] array) throws JSONException{
JSONArray jsonArray = new JSONArray();
Arrays.stream(array)
.forEach(jsonArray::put);
return jsonArray;
}
有什么方法可以使用流创建 JSONArray
吗?
最佳答案
您的代码有效,但您可以这样写 (jdk 8+
):
return Arrays.stream(array)
.collect(Collector.of(
JSONArray::new, //init accumulator
JSONArray::put, //processing each element
JSONArray::put //confluence 2 accumulators in parallel execution
));
再举一个例子(从 String
创建一个 List<String>
):
List<String> list = ...
String str = list.stream()
.collect(Collector.of(
StringBuilder::new,
StringBuilder::append,
StringBuilder::append,
StringBuilder::toString //last action of the accumulator (optional)
));
Looks nice, but compiler complaints:
error: incompatible thrown types JSONException in method reference .collect(Collector.of(JSONArray::new, JSONArray::put, JSONArray::put)
我在 jdk 13.0.1
上检查过这个和 JSON 20190722
并没有发现问题,除了 Expected 3 arguments, but found 1
在.collect(...)
.
( Gradle : implementation group: 'org.json', name: 'json', version: '20190722'
)
修复:
public static JSONArray arrayToJson(double[] array) throws JSONException {
return Arrays.stream(array).collect(
JSONArray::new,
JSONArray::put,
(ja1, ja2) -> {
for (final Object o : ja2) {
ja1.put(o);
}
}
);
}
注意:组合器不能是仅对 JSONArray::put
的方法引用因为这只会将一个数组放入另一个数组(例如 [[]]
),而不是按照预期的行为实际组合它们。
关于java - 如何在 Java 8 中使用流将集合/数组转换为 JSONArray,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48145457/