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;
*/
}
1
  • 2
    productList.removeIf(p -> p.getAttributeList().stream().map(Attribute::getAttributeId) .noneMatch(Predicate.isEqual​(x))); Commented Feb 18, 2020 at 17:51

2 Answers 2

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)

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

Comments

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

1 Comment

Calling remove on the list while you're iterating over it, is broken. In the best case, you get an exception.

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.