简体   繁体   English

如何使用Java 8 Stream API过滤集合中的列表

[英]How to use Java 8 Stream API for filter the list within a set

class A {
    List<B> b;
}

class B{
    boolean flag;

    B(boolean flag) {
        this.flag = flag;
    }
    //getter setter
}

B b1 = new B(true);
B b2 = new B(true);
B b3 = new B(false);

List<B> list1 = new ArrayList<>();
list1.add(b1);
list1.add(b2);
list1.add(b3);

Set<A> a = new HashSet<>();
a.add(list1);

There is a set of object A. 有一组对象A。

Object A contains a list of object B. B has a boolean property name 'flag' Using java 8 streams API, how to filter the set above such that it contains the list of B with boolean flag as true only. 对象A包含对象B的列表。B具有布尔属性名'flag'使用Java 8流API,如何过滤上面的集合,使其包含布尔标志为B的B列表。 ie b3 should be removed from list1. 即b3应该从list1中删除。 To keep it simple just added the single value. 为了简单起见,只需添加单个值。

You have a class A that contains a list of B ; 你有一个类, A包含列表B ; the goal is to remove, in each A , all the B that matches a condition. 目标是在每个A删除所有符合条件的B

The first solution is make a stream of the set of A s and map each of them to a new A where the list of B was filtered. 第一个解决方案是制作A集合的流,并将每个A映射到新的A ,其中过滤了B的列表。 Assuming that there is a constructor A(List<B> b) and the appropriate getters ( List<B> getB() in class A ; boolean isFlag() in class B ), you could have: 假设有一个构造函数A(List<B> b)和适当的吸气剂(类A List<B> getB() ;类B boolean isFlag() ),则可能有:

Set<A> set = new HashSet<>();

Set<A> filtered =
    set.stream()
       .map(a -> new A(a.getB().stream().filter(B::isFlag).collect(Collectors.toList())))
       .collect(Collectors.toSet());

A second solution is possible if you can modify the list of B s in-place, instead of creating a new one. 如果您可以就地修改B列表,而不是创建一个新的列表,则可能有第二种解决方案。 In such a case, you could have: 在这种情况下,您可能会:

set.forEach(a -> a.getB().removeIf(b -> !b.isFlag()));

which will remove all B where the flag is false for each A . 这将删除所有B其中该标志为false每个A

    @org.junit.Test
    public void test() {
        B b1 = new B(true);
        B b2 = new B(true);
        B b3 = new B(false);

        List<B> list1 = new ArrayList();
        list1.add(b1);
        list1.add(b2);
        list1.add(b3);

        Set<A> a = new HashSet();
        a.add(new A(list1));

        a.stream().forEach(aa -> aa.setB(aa.getB().stream().filter(B::isFlag).collect(Collectors.toList())));

        System.out.println(a);
    }

output: 输出:

[A{b=[B{flag=true}, B{flag=true}]}]
a.stream().forEach(l -> l.removeIf(b -> !b.getFlag()));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM