Skip to content
Advertisement

Java 8 modify stream elements

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.

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:

JavaScript

So I want to do something similar to below, but without modifying the collection. Assuming “list” is a List<SampleDTO>.

JavaScript

Advertisement

Answer

You must have some method/constructor that generates a copy of an existing SampleDTO instance, such as a copy constructor.

Then you can map each original SampleDTO instance to a new SampleDTO instance, and collect them into a new List :

JavaScript
User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement