Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calling objects method and return same object using functional api

At the moment I have:

cardLabels = cards.stream()
            .map(ImageSupplier::getCard)
            .map(JLabel::new)
            .collect(toList());

cardLabels.stream().forEach(container::add);

I can write lambda expression:

.map(c ->{ 
  JLabel label = new JLabel(c);
  container.add(label);
  return label;
 })

but it seems long. Is there something that I can call like .doStuff(container::add) with would return stream of JLabel?

like image 779
Artūrs Avatar asked Oct 18 '25 16:10

Artūrs


1 Answers

Perhaps you are looking for peek:

return cards.stream()
            .map(ImageSupplier::getCard)
            .map(JLabel::new)
            .peek(container::add);

Returns a stream consisting of the elements of this stream, additionally performing the provided action on each element as elements are consumed from the resulting stream.

This is an intermediate operation.

like image 88
Radiodef Avatar answered Oct 20 '25 05:10

Radiodef



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!