我想出了这段代码来过滤所有真实的对象,但我可以让它更整洁吗? Instream 和 boolean 转换让我很痒......
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>
依赖。这是最好的选择吗?
最佳答案
你可以使用 IntStream与 getBoolean :
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);
关于Java 8 : Is there a batter way to filter JSONArray?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57957238/