Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java 8 lambda list inside list filter

Tags:

java

lambda

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()) 
like image 397
Coder Avatar asked Nov 25 '17 03:11

Coder


1 Answers

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).

like image 166
Jacob G. Avatar answered Nov 18 '22 12:11

Jacob G.