"peek" is to be primarily used for debugging. What if I want to call a method on a stream in the middle of a stream, something that changes the state of the streamed object.
Stream.of("Karl", "Jill", "Jack").map(Test::new).peek(t->t.setLastName("Doe"));
I could do:
Stream.of("Karl", "Jill", "Jack").map(Test::new).map(t->{t.setLastName("Doe"); return t;});
But that seems ugly. Is this something that shouldn't be done or is there a better way to do this?
EDIT: forEach
works except that it's a terminal operation, and so you can't keep working on the stream afterwards. I would then expect to make a Collection, do forEach, then start streaming the Collection again.
EDIT: map(Class::processingMethod)
is what I'm doing now, but since processingMethod
simply returns this
, it seems to be a misuse of map. Plus, it doesn't really read like business logic.
FINAL EDIT: I accepted @Holger's answer. Stream.peek
cannot be expected to process all the elements on a Stream because it is not a terminal operation. The same goes for map
. Even though you might have terminated your stream with something that guarantees it will process all operations, you should not be writing code that expects every user to do so. So, to do processing you should use forEach
on a Collection
, then start streaming the Collection
again if you want to.