How can I reach a value of element "itemid" which has login "peter" and status "SLEEP" using streams in Java? Already I have a Jackson library and POJO classes in my project.
[
{
"itemid": "bf47",
"name": "test",
"workers": [
{
"user": {
"id": "7074",
"login": "john",
},
"status": [
{
"name": "WORK"
}
]
},
{
"user": {
"id": "1237",
"login": "peter",
},
"status": [
{
"name": "WORK"
},
{
"name": "SLEEP"
}
]
}
],
},
{
"itemid": "ea277",
"name": "test",
"workers": [
{
"user": {
"id": "2ce0",
"login": "robert"
},
"status": [
{
"name": "WORK"
}
]
}
],
}
]
I tried in the following manner, but it didn’t work:
String id = Arrays.stream(allItemId).flatMap(x->x.getworkers().stream())
.filter(x->x.getUser().getLogin().equals(peter))
.flatMap(x->x.getStatus().stream())
.filter(x->x.getName().equals("SLEEP")).map(x->x.getItemId).findFirst().get();
2
Answers
Flattening the stream will replace each
Item
with theirWorker
instances. Like so, you won’t be able anymore to retrieve theitemid
you need.In your case, you might want to consult the nested structures with the intermediate operation
filter
and keep only theItem
instances whoseUser
‘s login matchespeter
and whose statuses containsSLEEP
.Here is also a live demo at OneCompiler printing the
Item
with idbf47