Java strongly encourages you to use peek
method only for debugging purposes doc reference.
API Note:
This method exists mainly to support debugging, where you want to see the elements as they flow past a certain point in a pipeline:
And also, Java suggests avoiding stateful behaviour and side effects in stream operations doc reference.
Side-effects in behavioral parameters to stream operations are, in general, discouraged, as they can often lead to unwitting violations of the statelessness requirement, as well as other thread-safety hazards.
You can find more elaborated answers in this Stack Overflow thread In Java streams is peek really only for debugging?.
Answering to your question
I would suggest you to use forEach
method a couple of times or even use the regular for
loop.
list.forEach(e -> e.setTitle(e.getTitle() + " " + e.getBands().size()));
list.forEach(e -> e.getBands().forEach(b -> b.setName(b.getName() + "[" + b.getMembers().size() + "]")));
Tip on how to make code more readable
You can extract complicated lambdas (or their parts) to private methods to make code more readable. For example
list.forEach(this::changeEventTitle);
list.forEach(e -> e.getBands().forEach(this::changeBandName));
private void changeEventTitle(Event event) {
int size = event.getBands().size();
String newTitle = event.getTitle() + " " + size;
event.setTitle(newTitle);
}
private void changeBandName(Band band) {
int size = band.getMembers().size();
String newName = band.getName() + "[" + size + "]";
band.setName(newName);
}