0

How can I remove the element from the list if some inner list attribute value fails to meet the condition.The trick here is that attribute is itself a list and comparison is based on some attribute of that inner list. Please refer the below sample and help out to fill the comment section in code:

Object :

Class product{
 private String productId;
 private String productName;
 private List<Attribute> attributeList;

    public static class Attribute{
        private Long attributeId;
    }
}

Driver class :

Class Driver{
   List<product> productList = new ArrayList<product>();
   /*
   Remove the object from productList if attributeList doesn't contain attribute with attributeId = x;
*/
}
Nishant Varshney
  • 685
  • 2
  • 14
  • 34
  • 2
    `productList.removeIf(p -> p.getAttributeList().stream().map(Attribute::getAttributeId) .noneMatch(Predicate.isEqual​(x)));` – Holger Feb 18 '20 at 17:51

2 Answers2

5

What you can do it to stream over original list, and leave only objects which satisfy the condition. It might look something like this:

List<Product> filtered = productList.stream()
      .filter( p -> p.attributeList().stream().anyMatch( a -> a.attributeId.equals(x))
      .collect(Collectors.toList()) 

in this live we are actually checking if nested list contains at least one object with attributeId = x p.attributeList().stream().anyMatch( a -> a.attributeId.equals(x)

Anton Balaniuc
  • 10,889
  • 1
  • 35
  • 53
1

You can do a foreach loop and remove the unwanted elements. In "product" class you can insert a "FindInnerAtribute" function to search inside the Attributes list and return true if there is some.

List<product> productList = new ArrayList<product>();
for(product p : productList){
    if ( p.FindInnerAttribute(x) ){
        productList.remove(p);
    }
}

How to remove from list

  • 4
    Calling `remove` on the list while you're iterating over it, is broken. In the best case, you get an exception. – Holger Feb 18 '20 at 17:48