Java 8 modify stream elements

前端 未结 4 1228
生来不讨喜
生来不讨喜 2020-12-24 14:26

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

4条回答
  •  情书的邮戳
    2020-12-24 14:54

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

提交回复
热议问题