Home » Java » arraylist – Remove a element from List of objects based on inner object list value in java-Exceptionshub

arraylist – Remove a element from List of objects based on inner object list value in java-Exceptionshub

Posted by: admin February 25, 2020 Leave a comment

Questions:

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;
*/
}
How to&Answers:

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)

Answer:

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