0

I need to get value of a particular key from all JSONObjects in a JSONArray (example below).

I have a traditional loop approach, I am wondering if there is a better way to do this. Maybe using streams?

private static Collection<? extends String> someMethod(JSONArray jsonArray) {
    Set<String> setToReturn = new HashSet<>();
    for (int i = 0; i < jsonArray.length(); i++) {
        setToReturn.add(jsonArray.getJSONObject(i).getString("key"));
    }
    return setToReturn;
}

An Example JSON is as follows:

"someArray": {
    "someObject": [
        {
            "key": "001",
            "key1": "value",
            "key2": "value",
            "key3": "value"
        }
    ],
    "someObject2": [
        {
            "key": "002",
            "key1": "value",
            "key2": "value",
            "key3": "value"
        }
    ],
    "someObject3": [
        {
            "key": "003",
            "key1": "value",
            "key2": "value",
            "key3": "value"
        }
    ],
}

Basically, I need the "key" from each JSONObject into a Set or a List.

Example output: [001, 002, 003]

The code above works, I am wondering if there is a better way to do this. Assume that there are thousands of such JSONObjects. I am using org.json library.

Thanks in advance.

1 Answer 1

1

There is no better way to do this. Looping through the array is O(n) time complexity and getting the value from the object is O(1) time complexity. Obviously, you will need to visit each value to add it to the list, which is why the total time complexity must be O(n). Inserting into a List might be slightly faster than a HashSet based on the values you get, but this is the most efficient way

Sign up to request clarification or add additional context in comments.

1 Comment

Maybe using streams?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.