Java 8修改流元素 [英] Java 8 modify stream elements

查看:376
本文介绍了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或"normal"的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<SampleDTO>.

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变为一个新的List:

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修改流元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆