【问题标题】:Java 8: Is there a batter way to filter JSONArray?Java 8:有没有更好的过滤 JSONArray 的方法?
【发布时间】:2019-09-16 12:47:44
【问题描述】:

我想出了这个代码来过滤所有真实的对象,但我可以让它更整洁吗?流内和布尔转换让我很痒......

import org.json.JSONArray;
import org.json.JSONObject;

JSONArray arr = new JSONArray();
arr.put(false);
arr.put(true);
arr.put(false);

//JSONArray is a list of objects
boolean b = IntStream.range(0, arr.length())
        .filter(index -> ((boolean) arr.get(index)) == true)
        .findAny()
        .isPresent();

我用

<groupId>org.json</groupId>
<artifactId>json</artifactId>
<version>20180813</version>

依赖。这是最好的选择吗?

【问题讨论】:

  • 请提供有关从何处获取 JSONArray 的信息。这是图书馆吗?
  • @DaveG 使用导入更新了代码

标签: java java-8 java-stream


【解决方案1】:

您可以将IntStreamgetBoolean 一起使用:

JSONArray arr = new JSONArray();
arr.put(false);
arr.put(true);
arr.put(false);

//JSONArray is a list of objects
boolean b = IntStream.range(0, arr.length())
        .anyMatch(arr::getBoolean);

System.out.println(b);

输出

true

作为替代方案,您可以使用以下内容:

boolean b = StreamSupport.stream(arr.spliterator(), false)
                .anyMatch(Boolean.TRUE::equals);

上述解决方案确实处理了 JSONException 问题,例如它为以下输入返回 true

JSONArray arr = new JSONArray();
        arr.put(false);
        arr.put(1);
        arr.put(true);

【讨论】:

  • 需要处理JSONException。
  • @DanielMesejo IntStream.range(0, arr.length()) .anyMatch(arr::getBoolean);绝对做的工作!谢谢!
【解决方案2】:

试试这个:

boolean b = arr.toList().stream().anyMatch(x -> (Boolean) x);

【讨论】:

    猜你喜欢
    • 2015-10-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-06-30
    • 1970-01-01
    • 2023-03-30
    相关资源
    最近更新 更多