Java 8 修改流元素

Java 8 modify stream elements(Java 8 修改流元素)

本文介绍了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 修改流元素

基础教程推荐