Java lambda 表达式——映射然后修改列表?

2022-01-22 00:00:00 lambda java-8 java java-stream

使用 Java 8 lambda 表达式,我正在尝试做这样的事情.

Using a Java 8 lambda expression, I'm trying to do something like this.

List<NewObject> objs = ...;
for (OldObject oldObj : oldObjects) {
  NewObject obj = oldObj.toNewObject();
  obj.setOrange(true);
  objs.add(obj);
}

我写了这段代码.

oldObjects.stream()
  .map(old -> old.toNewObject())
  .forEach({new.setOrange("true")})
  .collect(Collectors.toList()); 

这是无效代码,因为我试图对 .forEach() 返回的内容执行 .collect(),但 forEach 无效且不返回列表.

This is invalid code because I'm then trying to do .collect() on what's returned by .forEach(), but forEach is void and does not return a list.

这应该如何构建?

推荐答案

你可以使用Streampeek方法,返回Stream 因为它是一个中间操作.它通常不应该有副作用(它应该是无干扰的"),但在这种情况下,我认为副作用 (setOrange(true)) 是有意的并且是很好.

You can use Stream's peek method, which returns the Stream because it's an intermediate operation. It normally isn't supposed to have a side effect (it's supposed to be "non-interfering"), but in this case, I think the side effect (setOrange(true)) is intended and is fine.

List<NewObject> newObjects =
    oldObjects.stream()
        .map(OldObject::toNewObject)
        .peek( n -> n.setOrange(true))
        .collect(Collectors.toList());

它与您的非流代码一样冗长,因此您可以选择使用哪种技术.

It's about as verbose as your non-streams code, so you can choose which technique to use.

相关文章