"peek" should be used mainly for debugging. What if I want to call a method in a stream in the middle of the stream, which will change the state of the stream 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 should not be done, or is there a better way to do this?
EDIT: It forEachworks, except that it is a terminal operation, and therefore you cannot continue to work with the stream later. Then I would expect to make a collection, make forEach, and then start building the collection again.
EDIT: map(Class::processingMethod)- this is what I am doing now, but since it processingMethodjust returns this, it seems to be using the map incorrectly. In addition, it really does not read like business logic.
FINAL EDITOR: I accepted @Holger's answer. Stream.peekyou cannot expect all elements in the stream to be processed, because this is not a terminal operation. The same goes for map. Despite the fact that you could stop the thread with something that guarantees its processing of all operations, you should not write code that expects each user to do this. So, to do the processing, you have to use forEachon Collection, and then start the thread again Collectionif you want.
source
share