Remove all keys except one from JSONObject

Harshal Parekh :

I have a JSONObject (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 keys except a. Is there an elegant way to do this other than my naive approach?

Iterator<String> keys = jsonObject.keys();
while (keys.hasNext()) {
    if (!keys.next().equals("a")) {
        keys.remove();
    }
}

Expected output:

{"a": "a"}
Naman :

I believe a simpler way to do that would be using removeIf as

jsonObject.keySet().removeIf(k -> !k.equals("a"));

Guess you like

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