基于列表的Java 8流操作

时间:2019-06-24 13:31:44

标签: java java-8 java-stream

我有两个清单。第一个是字符串列表-一个列表,第二个包含新类的列表,比方说B类。

B类包含String字段,例如example1,example2,example3,example4等。

我尝试了类似的方法,但是我认为它可以处理克隆集合,并且不会将特定值更改为null。

listOfB.stream().flatMap(p -> Stream.of(p.getExample1(),p.getExample2(), 
p.getExample3(), p.getExample4()))
            .forEach(i -> {
                if (listOfA.contains(i)) {
                    i = null
                }
            });

我要实现的是流式处理B对象列表,获取所有示例字段(从1到4),然后检查A列表是否至少包含示例字段值之一,如果是,则设置此特定示例字段为空。

3 个答案:

答案 0 :(得分:1)

要仅使用一个流执行此操作,您必须在lambda内部通过一系列if检查。

public void stack() {
    List<String> aList = Arrays.asList("foo2", "baz4");

    B b1 = new B("foo1", "foo2", "foo3", "foo4");
    B b2 = new B("bar1", "bar2", "bar3", "bar4");
    B b3 = new B("baz1", "baz2", "baz3", "baz4");

    List<B> bList = Stream.of(b1, b2, b3).peek(b -> {
        if (aList.contains(b.getExample1())) {
            b.setExample1(null);
        }
        if (aList.contains(b.getExample2())) {
            b.setExample2(null);
        }
        if (aList.contains(b.getExample3())) {
            b.setExample3(null);
        }
        if (aList.contains(b.getExample4())) {
            b.setExample4(null);
        }
    }).collect(Collectors.toList());

    System.out.println(bList);
}

输出:

  

B [example1 = foo1,example2 = null,example3 = foo3,example4 = foo4],

     

B [example1 = bar1,example2 = bar2,example3 = bar3,example4 = bar4],

     

B [example1 = baz1,example2 = baz2,example3 = baz3,example4 = null]

答案 1 :(得分:0)

更改lambda参数对lambda无效。您要寻找的方法是.filter()

.filter(i -> !listOfA.contains(i))

尽管用forEach代替filter并不会起到太大作用,因为filter不是终端操作。注意它如何返回Stream<T>。如果您希望更改在listOfB中生效,则需要将流收集到新列表中并重新分配。

List<String> list = stream.collect(Collectors.toList())

答案 2 :(得分:0)

您可以执行以下操作:使用set代替list

bList = bList.stream().map(b -> b.modify(aSet))
            .collect(Collectors.toList());

OR

bList.replaceAll(b -> b.modify(aSet));

并在B类中定义一个方法:

public B modify(Set<String> set) {
    this.example1 = set.contains(this.example1) ? null : this.example1;
    this.example2 = set.contains(this.example2) ? null : this.example2;
    this.example3 = set.contains(this.example3) ? null : this.example3;
    this.example4 = set.contains(this.example4) ? null : this.example4;
    return this;
}