I have a JSONArray (org.json) like this:
[
{ \"a\": \"a\" },
{ \"b\": \"a\" },
{ \"c\": \"a\" },
{ \"d\": \"a\" },
{ \"e\": \"a\" },
{ \"
What we can do is map all JSONObjects to a List if they contain the key a
. Then we can create a new JSONArray from that List of objects, which in this case is only 1.
You can technically do this in a single line but it looks a bit worse IMO.
List objects = IntStream.range(0, array.length())
.filter(index -> array.get(index) instanceof JSONObject)
.mapToObj(array::getJSONObject)
.filter(object -> object.has("a"))
.collect(Collectors.toList());
JSONArray reduced = new JSONArray(objects);