Java 8 modify stream elements(Java 8 修改流元素)
问题描述
我想用 Java 8 编写纯函数,它将一个集合作为参数,对该集合的每个对象应用一些更改,并在更新后返回一个新集合.我想遵循 FP 原则,所以我不想更新/修改作为参数传递的集合.
I wanted to write pure function with Java 8 that would take a collection as an argument, apply some change to every object of that collection and return a new collection after the update. I want to follow FP principles so I dont want to update/modify the collection that was passed as an argument.
有没有什么方法可以用 Stream API 做到这一点,而无需先创建原始集合的副本(然后使用 forEach 或正常"for 循环)?
Is there any way of doing that with Stream API without creating a copy of the original collection first (and then using forEach or 'normal' for loop)?
下面的示例对象,假设我想将文本附加到对象属性之一:
Sample object below and lets assume that I want to append a text to one of the object property:
public class SampleDTO {
private String text;
}
所以我想做类似下面的事情,但不修改集合.假设列表"是一个 List
.
So I want to do something similar to below, but without modifying the collection. Assuming "list" is a List<SampleDTO>
.
list.forEach(s -> {
s.setText(s.getText()+"xxx");
});
推荐答案
您必须有一些方法/构造函数来生成现有 SampleDTO
实例的副本,例如复制构造函数.
You must have some method/constructor that generates a copy of an existing SampleDTO
instance, such as a copy constructor.
然后您可以将每个原始 SampleDTO
实例map
到一个新的SampleDTO
实例,并将它们collect
放入一个新的列表
:
Then you can map
each original SampleDTO
instance to a new SampleDTO
instance, and collect
them into a new List
:
List<SampleDTO> output =
list.stream()
.map(s-> {
SampleDTO n = new SampleDTO(s); // create new instance
n.setText(n.getText()+"xxx"); // mutate its state
return n; // return mutated instance
})
.collect(Collectors.toList());
这篇关于Java 8 修改流元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:Java 8 修改流元素


- GC_FOR_ALLOC 是否更“严重"?在调查内存使用情况时? 2022-01-01
- 如何使 JFrame 背景和 JPanel 透明且仅显示图像 2022-01-01
- Eclipse 的最佳 XML 编辑器 2022-01-01
- java.lang.IllegalStateException:Bean 名称“类别"的 BindingResult 和普通目标对象都不能用作请求属性 2022-01-01
- 如何指定 CORS 的响应标头? 2022-01-01
- 将 Java Swing 桌面应用程序国际化的最佳实践是什么? 2022-01-01
- 未找到/usr/local/lib 中的库 2022-01-01
- 获取数字的最后一位 2022-01-01
- 转换 ldap 日期 2022-01-01
- 在 Java 中,如何将 String 转换为 char 或将 char 转换 2022-01-01