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 aft
Streams are immutable like strings so you cannot get around needing to create a new stream/list/array
That being said you can use .Collect() to return a new collection post change so
List<Integer> result = inList.stream().map().Collect()
To make this more elegant way I would suggest create a Method
with in the 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 like:
List<SampleDTO> output =list.stream().map(SampleDTO::getSampleDTO).collect(Collectors.toList();
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
:
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());
I think it would be better, especially if doing multi-threaded work, to stream the original list into a new modified list or whatever else is desired.
The new list or map or whatever other structure you desire can be created as part of the streaming process.
When the streaming process is completed, simply swap the original with the new.
All of this should occur in a synchronized block.
In this manner, you get the maximum performance and parallelism for the reduce or whatever it is you are doing, and finish with an atomic swap.