How to convert a collection/ array into JSONArray

2019-01-26 21:13发布

问题:

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?

回答1:

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<String>):

List<String> 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)  
                 ));


回答2:

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);
        }
    });