skip to Main Content

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


  1. String id = allItemId.stream()
        .filter(item -> item.getWorkers().stream()
                .anyMatch(worker ->
                        "peter".equals(worker.getUser().getLogin()) &&
                        worker.getStatus().stream().anyMatch(status -> "SLEEP".equals(status.getName()))
                )
        )
        .findAny()
        .map(Item::getItemid)
        .orElse(null);
    
    Login or Signup to reply.
  2. Flattening the stream will replace each Item with their Worker instances. Like so, you won’t be able anymore to retrieve the itemid you need.

    In your case, you might want to consult the nested structures with the intermediate operation filter and keep only the Item instances whose User‘s login matches peter and whose statuses contains SLEEP.

    Item res = Arrays.stream(allItemId).
                    filter(item -> item.getWorkers().stream().anyMatch(worker -> worker.getUser().getLogin().equals("peter")
                            && worker.getStatus().stream().anyMatch(status -> status.getName().equals("SLEEP"))))
                    .findAny().orElse(null);
    

    Here is also a live demo at OneCompiler printing the Item with id bf47

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search