如何在java 8中使用流将集合/数组转换为JSONArray [英] How to convert a collection/ array into JSONArray using stream in java 8

查看:3935
本文介绍了如何在java 8中使用流将集合/数组转换为JSONArray的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个双数组,我需要使用java流将数组转换为JSONArray。我尝试使用forEach(共享可变性),这会导致数据丢失。

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

我有什么方法可以使用流创建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
                     ));

再来一个例子(从一个 String 创建一个列表< String>

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

这篇关于如何在java 8中使用流将集合/数组转换为JSONArray的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆