根据java中的内部对象列表值从对象列表中删除元素

Nis*_*ney 0 java collections arraylist remove-if java-8

如果某些内部列表属性值不满足条件,如何从列表中删除元素。这里的技巧是该属性本身是一个列表,比较基于该内部列表的某些属性。请参考以下示例并帮助填写代码中的注释部分:

目的 :

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

    public static class Attribute{
        private Long attributeId;
    }
}
Run Code Online (Sandbox Code Playgroud)

驱动程序类:

Class Driver{
   List<product> productList = new ArrayList<product>();
   /*
   Remove the object from productList if attributeList doesn't contain attribute with attributeId = x;
*/
}
Run Code Online (Sandbox Code Playgroud)

Ant*_*iuc 5

你可以做什么来流过原始列表,只留下满足条件的对象。它可能看起来像这样:

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

在这个直播中,我们实际上是在检查嵌套列表是否至少包含一个对象 attributeId = x p.attributeList().stream().anyMatch( a -> a.attributeId.equals(x)