如何在 Stream 链中调用 setter

2022-01-22 00:00:00 java-8 java java-stream

如何在不使用 forEach() 的情况下调用 Stream 链中的 setter?

How can I call the setter in chain of Stream without using forEach()?

List<Foo> newFoos = foos.stream()
        .filter(foo -> Foo::isBlue)
        .map(foo -> foo.setTitle("Some value")) //I am unable to use this because also changing the data type into Object
        .collect(Collectors.toList());

推荐答案

像这样使用 peek 方法.它不影响流.

Use peek method like this. It does not affect stream.

    List<Foo> newFoos = foos.stream()
            .filter(Foo::isBlue)
            .peek(foo -> foo.setTitle("Some value"))
            .collect(Collectors.toList());

相关文章