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:
one more example (create a
String
fromList<String>
):JSONArray
is not thread safe. If you are using parallel stream you should synchronize the operation.