42

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:

public class SampleDTO {
    private String text;
}

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");
});
1
  • 2
    I'd say that this does go a little against the principle of functional programming here. The idea is to not mutate state, but create new state as a product of the function. That's why, instead of mutating the original list, you should be using the map function provided by the Java stream API to create a new list. Jul 11, 2016 at 8:43

6 Answers 6

70

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());
1
5

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();
4
  • @FedericoPeraltaSchaffner Thanks for the comment and downvote . I have fixed this . now it will compile Jun 10, 2017 at 5:10
  • I downvoted because your answer had 1 vote and I wanted to promote other answers which were correct, sorry if that was too harsh. Now that you have corrected it, I have not only reverted my downvote but also upvoted.
    – fps
    Jun 10, 2017 at 5:19
  • 1
    However, now the original object is modified, and OP wanted to not mutate neither the original list nor its elements. You should consider creating a copy of the original object with its text attribute modified.
    – fps
    Jun 10, 2017 at 5:22
  • 5
    The method getSampleDTO modifying its text? Vary bad naming of the method and very nasty side-effect Jan 18, 2019 at 13:12
5

I think a cleaner and more readable solution is:

List<SampleDTO> unmodifiable = Arrays.asList(new SampleDTO("1"), new SampleDTO("2"));

List<SampleDTO> modified = unmodifiable.stream()
            .map(s -> new SampleDTO(s.getText())) // '.map(SampleDTO::new)' with copy constructor
            .peek(s -> s.setText(s.getText() + "xxx"))
            .collect(Collectors.toList());

Or if you have copy constructor of SampleDTO you can replace map function with .map(SampleDTO::new).

peek function will provide action on elements of Stream without changing result type of Stream.

4
  • 3
    Note: You should not use peek() in production code. Only for debugging.
    – alex87
    Mar 4, 2021 at 12:07
  • peek() is not quite intended to be used to change stream elements (although it surely can, and, according to documentation, "exists mainly to support debugging, where you want to see the elements as they flow past a certain point in a pipeline"
    – ghost28147
    Jan 20, 2022 at 13:59
  • 3
    @ghost28147 it means that 'peek' is lazy method which can't be executed for all elements in stream, for example when you use method 'findFirst' (you can find first element in stream and 'peek' will not be executed for other elements), but if you use it before 'collect' method, which means that all your elements will be used for inserting in collection, you can use 'peek'. In general you can use 'peek' method if you know how streams work inside. Docs says "mainly to support debugging", not "must't be used in production".
    – Alex
    Jan 21, 2022 at 10:17
  • @alex87 see my comment above.
    – Alex
    Jan 21, 2022 at 10:17
3

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()
2

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.

1

If you use Lombok, you can use immutable setters.

.map(s -> s.withText(s.getText() + "..."))

See: https://projectlombok.org/features/With

1
  • Damn, I like that!
    – C. Oltan
    Aug 8, 2022 at 8:42

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.