1

I need your help because I want to update a parent list and a child list using stream and lambda if possible.

The parent is Event it contains a list of Band and the list of Band contains a list of Member.

I have to update the title of each Event by adding the size of the band list (sample : "U2 Concert Event [5]". I also have to update each band in order to add the size of the Member list in the name of the Band (sample: U2 [3])

How can I achieve this using stream and lambda?

This is my actual code:

list.stream().peek(e -> e.setTitle(e.getTitle()+" "+e.getBands().size()))
        .forEach(updatedEvent -> updatedEvent.getBands().stream()
                .forEach(b -> b.setName(b.getName()+"["+b.getMembers().size()+"]")));
Mark Rotteveel
  • 100,966
  • 191
  • 140
  • 197

1 Answers1

2

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);
}
geobreze
  • 2,274
  • 1
  • 10
  • 15