Issue
I came up with this code to filter all the true objects, but can I have it even neater? The intstream and boolean casting are itching me...
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();
I use
<groupId>org.json</groupId>
<artifactId>json</artifactId>
<version>20180813</version>
dependency. Is it the best selection?
Solution
You could use IntStream with 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);
Output
true
As an alternative you could use the following:
boolean b = StreamSupport.stream(arr.spliterator(), false)
.anyMatch(Boolean.TRUE::equals);
The above solution does handle the JSONException problem, for instance it returns true
for the following input:
JSONArray arr = new JSONArray();
arr.put(false);
arr.put(1);
arr.put(true);
Answered By - Dani Mesejo