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

Java lambda expression -- mapping and then modifying a list?(Java lambda 表达式——映射然后修改列表?)
本文介绍了Java lambda 表达式——映射然后修改列表?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用 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.

这篇关于Java lambda 表达式——映射然后修改列表?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

How to convert Lambda into simple Java function(如何将Lambda转换为简单的Java函数)
AWS S3 Event notification using Lambda function in Java(在Java中使用Lambda函数的AWS S3事件通知)
When testing JButton my lambda expression works, but actionPerformed does not(在测试JButton时,我的lambda表达式可以工作,但actionPerform不能)
AWS Lambda using incorrect classfiles from a Multi-Release JAR?(AWS Lambda使用来自多版本JAR的不正确类文件?)
Multiple null checks in Java 8(Java 8中的多个空检查)
Using Java 8 Optional for List of String as output(使用Java 8可选的字符串列表作为输出)