Java 8 modify stream elements

前端 未结 4 1223
生来不讨喜
生来不讨喜 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: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 output =list.stream().map(SampleDTO::getSampleDTO).collect(Collectors.toList();
    

提交回复
热议问题