使用函数 api 调用对象方法和 return 同一对象

Calling objects method and return same object using functional api

目前我有:

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

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

我会写lambda表达式:

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

不过好像很长。有什么我可以用 .doStuff(container::add)JLabel 的 return 流调用的东西吗?

也许您正在寻找 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.

最好避免从流内部改变外部数据结构。如果 container 不是同步的或并发的并且要使流并行,则结果将不可预测。

与其尝试将更多内容塞入流表达式,不如简化第二条语句:

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

container.addAll(cardLabels);

这样一来,您的逻辑就不会因将 stream() 更改为 parallelStream() 而意外搞砸了。