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

Mostwanted Mani :

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?

kozmo :

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

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 (Gradle :compile group: 'org.json', name: 'json', version: '20190722')

I didn't find problems except of Expected 3 arguments but found 1 in .collect(...).

Fix:

public static JSONArray arrayToJson(double[] array) throws JSONException {
    return Arrays.stream(array).collect(
            JSONArray::new,
            JSONArray::put,
            JSONArray::put
    );
}

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=459249&siteId=1