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.