How to convert a collection/ array into JSONArray using stream in java 8
Your code works, but you can write something like this (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
));
one more example (create a String
from 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)
I checked this on jdk 13.0.1
and JSON 20190722
and didn't find problems except of Expected 3 arguments, but found 1
in .collect(...)
.
(Gradle : implementation group: 'org.json', name: 'json', version: '20190722'
)
Fix:
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);
}
}
);
}
Note: The combiner cannot be a method reference to just JSONArray::put
because this will just put one array into the other (e.g. [[]]
) instead of actually combining them as is the desired behavior.
JSONArray
is not thread safe. If you are using parallel stream you should synchronize the operation.
Arrays
.stream(array)
.parallel()
.forEach(e -> {
synchronized(jsonArray) {
jsonArray.put(e);
}
});