Michael Galos
Michael Galos

Reputation: 1085

Filtering a list by value of item in child list

I have a list of objects List, for each instance of those 'Place' objects there contains a number of members and lists. I want to be able to filter the parent list based on the existence of a value in a child list.

These lists of objects are JSON being converted into a plain old Java object using Jackson.

Using the example data below (that has been converted into a java object in my actual code, but is shown here in JSON for readability) I want to filter out all places which do not have product 'C'.

{
  "places": [
    {
      "Name": "ANAME",
      "location": "A",
      "type": "R",
      "date": "2017-03-27",
      "availableProducts": [
        {
          "product": "A",
          "price": 15.00
        },
        {
          "product": "B",
          "price": 15.00
        },
        {
          "product": "C",
        },
        {
          "product": "D",
        }
      ]
     },
    {
      "Name": "NNAME",
      "location": "A",
      "type": "R",
      "date": "2017-03-27",
      "availableProducts": [
        {
          "product": "E",
          "price": 15.00
        },
        {
          "product": "F",
          "price": 15.00
        }
      ]
    }
  ]
}

I've gotten this far, which obviously won't work since it will only look at the first product:

places.removeIf(p -> !p.getAvailableProducts().get(0).getProduct.equals("C"));

Upvotes: 1

Views: 65

Answers (1)

Viet
Viet

Reputation: 3409

Try this:

places.removeIf(p -> !p.getAvailableProducts().stream().anyMatch(x -> x.getProduct.equals("C")));

Upvotes: 2

Related Questions