Java 8 change stream elements

I wanted to write a pure function with Java 8 that would take the collection as an argument, apply some change to each object of this collection, and return a new collection after the update. I want to follow the principles of FP, so I do not want to update / change the collection that was passed as an argument.

Is there a way to do this using the Stream API without first creating the first collection (and then using forEach or "normal" for the loop)?

An example of an object is below and suppose I want to add text to one of the properties of the object:

public class SampleDTO { private String text; } 

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

 list.forEach(s -> { s.setText(s.getText()+"xxx"); }); 
+8
java java-8 java-stream
source share
4 answers

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

Then you can map add each instance of SampleDTO to a new instance of SampleDTO and collect to 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()); 
+12
source share

To make this a more elegant way, I would suggest creating a Method in a class.

  public class SampleDTO { private String text; public String getText() { return text; } public void setText(String text) { this.text = text; } public SampleDTO(String text) { this.text = text; } public SampleDTO getSampleDTO() { this.setText(getText()+"xxx"); return this; } } 

and add it as:

 List<SampleDTO> output =list.stream().map(SampleDTO::getSampleDTO).collect(Collectors.toList(); 
+2
source share

Streams are immutable like strings, so you cannot get around to creating a new stream / list / array

In doing so, you can use .Collect () to return a new collection change message to

 List<Integer> result = inList.stream().map().Collect() 
+1
source share

I think it would be better, especially if you are doing multi-threaded work, so that the stream from the original list to a new modified list or something else is needed.

A new list or map, or any other structure you desire, can be created as part of the streaming process.

When the streaming process is complete, simply replace the original with a new one.

All this should happen in a synchronized block.

This way you get maximum performance and parallelism to reduce or what you do, and end up with an atomic swap.

+1
source share

All Articles