Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to call setter in chain of Stream

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());
like image 466
richersoon Avatar asked Feb 13 '16 08:02

richersoon


1 Answers

forEach seems like a more suited tool for the job, but if you don't want to use it you could always define an anonymous multi-line lambda:

List<Foo> foos = foos.stream()
        .filter(foo -> Foo::isBlue)
        .map(foo -> {
                        foo.setTitle("Some value");
                        return foo;
                    })
        .collect(Collectors.toList()); 
like image 99
Mureinik Avatar answered Sep 22 '22 22:09

Mureinik