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 修改流元素


基础教程推荐
- 在 Java 中创建日期的正确方法是什么? 2022-01-01
- Java Swing计时器未清除 2022-01-01
- 不推荐使用 Api 注释的描述 2022-01-01
- 如何在 Spring @Value 注解中正确指定默认值? 2022-01-01
- 从 python 访问 JVM 2022-01-01
- Java 实例变量在两个语句中声明和初始化 2022-01-01
- 如何在 JFrame 中覆盖 windowsClosing 事件 2022-01-01
- 多个组件的复杂布局 2022-01-01
- 验证是否调用了所有 getter 方法 2022-01-01
- 大摇大摆的枚举 2022-01-01