How to convert a collection/ array into JSONArray using stream in java 8

回眸只為那壹抹淺笑 提交于 2019-12-29 07:05:09

问题


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


来源:https://stackoverflow.com/questions/48145457/how-to-convert-a-collection-array-into-jsonarray-using-stream-in-java-8

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!