```java
public class StreamTest {
private List<C> initialSequence() {
var res = new ArrayList<C>();
var rand = new Random(0);
for (int i = 0; i < 10; i++) {
C c = new C();
c.setId(i);
c.setCurrent(rand.nextInt(1000));
res.add(c);
}
return res;
}
@
Test public void stream() {
List<C> sequence = initialSequence();
System.out.println("before");
output(sequence);
C finalResult =
sequence.stream().reduce(new C(), (pre, now) -> {
Integer accumulative = Optional.ofNullable(pre.getAccumulative()).orElse(0);
now.setAccumulative(accumulative + now.getCurrent());
return now;
});
System.out.println("after");
output(sequence);
}
private void output(List<C> sequence) {
for (C c : sequence) {
System.out.println(String.format("id: %s, acc: %d", c.getId(), c.getAccumulative()));
}
}
static class C {
private Integer id;
private Integer accumulative;
private Integer current;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public Integer getAccumulative() {
return accumulative;
}
public void setAccumulative(Integer accumulative) {
this.accumulative = accumulative;
}
public Integer getCurrent() {
return current;
}
public void setCurrent(Integer current) {
this.current = current;
}
}
}
```
无视 reduce 的结果即可.