Java 8 modify stream elements

前端 未结 4 1193
生来不讨喜
生来不讨喜 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:43

    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()
    
    0 讨论(0)
  • 2020-12-24 14:47

    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();
    
    0 讨论(0)
  • 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<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());
    
    0 讨论(0)
  • 2020-12-24 15:00

    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.

    0 讨论(0)
提交回复
热议问题