8

Sample JSON

[
  {
    "id": "1",
    "products": [
      {
        "id": "333",
        "status": "Active"
      },
      {
        "id": "222",
        "status": "Inactive"
      },
      {
        "id": "111",
        "status": "Active"
      }

    ]
  },
  {
    "id": "2",
    "products": [
      {
        "id": "6",
        "status": "Active"
      },
      {
        "id": "7",
        "status": "Inactive"
      }
    ]
  }
]

I want to retrieve list of objects that have at least one active product.

Below code returns list of products but I want a list of ProdcutResponse. Any way to do this?

 response.stream()
 .map(ProductResponse::getProducts)
 .filter(s -> "Active".equals(s.getType()))
 .collect(Collectors.toList()) 

1 Answer 1

8

Because you didn't show much code, this will be a shot in the dark. My main suggestion would be to not map the Stream<ProductResponse> to a Stream<List<Product>> before collecting it to a list:

response.stream()
        .filter(pr -> pr.getProducts().stream().anyMatch(s -> "Active".equals(s.getType())))
        .collect(Collectors.toList());

You can change anyMatch to allMatch if you want the List<ProductResponse> to contain onlyProducts with active types (whatever that means).

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

1 Comment

@Forhad The time complexity is O(n^2). Some pre-computation would be required to optimize it.

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.