I have this JSON API response list:
[
{
"id": "demoType",
"label": "Demo Type",
"option": [
"MAJOR"
]
},
{
"id": "test",
"label": "test",
"option": [
{
"name": "testOne",
"id": "1111",
"demolId": "demoid-1"
},
{
"name": "testTwo",
"id": "2222",
"demoId": "demoid-3"
},
{
"name": "testThree",
"id": "3333",
"demolId": "demo-2"
}
]
},
{
"id": "sampleType",
"label": "sample",
"option": [
{
"name": "sampleA",
"id": "4444"
}
]
},
{
"id": "runType",
"label": "run one",
"option": [
{
"name": "runA",
"id": "eaf7d6a5-2038-45a0-9f06-6410694e5354",
"demoId": "demolid-1"
}
]
},
{
"id": "city",
"label": "City",
"option": [
"york",
"tampa"
]
}
]
I have a corresponding responseDTO:
@Data
@AllArgsConstructor
@NoArgsConstructor
public class DemoResponse {
public String id;
public String label;
public ArrayList<Object> option;
}
The API response has got a property called option
, which appears multiple times in a nested list. What I want to achieve is to collect the values of all the options properties to a list.
I tried like this:
DemoResponse[] response = (BaseClient.getResponse().as(DemoResponse[].class));
List<String> optionlList =
response.stream().map(newList -> newdList.toString()).collect(Collectors.toList());
stream
could not be compiled. I am convinced that what I am doing is obviously wrong, but I am not sure how to achieve what I want which is to get all the values of the option fields in the API response and collect them into a list.
2
Answers
There is no
.stream()
over Array, you need to useArrays.stream
You can do like below, stream through the
response
array andflatMap
the option and collect to a single listYour
optionList
would be