How to call a setter in a thread chain

How can I call setter in a Stream chain 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());
+4
source share
2 answers

Use a peek method similar to this. This does not affect the flow.

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

forEach seems like a more suitable tool for the job, but if you don't want to use it, you can always define an anonymous multiline lambda:

List<Foo> foos = foos.stream()
        .filter(foo -> Foo::isBlue)
        .map(foo -> {
                        foo.setTitle("Some value");
                        return foo;
                    })
        .collect(Collectors.toList()); 
0
source

Source: https://habr.com/ru/post/1628615/


All Articles