Remove all elements except one from JSONArray of JSONObjects

Harshal Parekh :

I have a JSONArray (org.json) like this:

[
    { "a": "a" },
    { "b": "a" },
    { "c": "a" },
    { "d": "a" },
    { "e": "a" },
    { "f": "a" },
    { "g": "a" }
]

I would like to remove all the JSONObjects that do not have the key a. Is there a better way to do other than my naive approach?

Iterator objects = jsonArray.iterator();
while (objects.hasNext()) {
    Object o = objects.next();
    if (o instanceof JSONObject && !((JSONObject) o).has("a")) {
        objects.remove();
    }
}

Expected output:

[{"a": "a"}]
ETO :

If you're seeking a functional style solution, you can wrap the Iterator into a Stream and then do whatever you want.

One of the functional solutions:

JSONArray newJsonArray =
        StreamSupport.stream(jsonArray.spliterator(), false)
                     .filter(JSONObject.class::isInstance)
                     .map(JSONObject.class::cast)
                     .filter(j -> j.has("a"))
                     .collect(collectingAndThen(toList(), JSONArray::new));

Note: The solution above does not modify the original JSONArray. Following the principles of functional programming one should prefer collecting into a new object rather than modifying the existing one.

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=409680&siteId=1