Im having a double array , I need to convert the array into a JSONArray using java streams. I tried using forEach (shared mutability) which leads to loss of data.
public static JSONArray arrayToJson(double[] array) throws JSONException{
JSONArray jsonArray = new JSONArray();
Arrays.stream(array)
.forEach(jsonArray::put);
return jsonArray;
}
Is there any way I could to create JSONArray using streams?
解决方案
Your code works, but you can write something like this:
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):
List list = ...
String str = this.list
.stream()
.collect(Collector.of(
StringBuilder::new,
(b ,s) -> b.append(s),
(b1, b2) -> b1.append(b2),
StringBuilder::toString //last action of the accumulator (optional)
));