Update: As Holger pointed out in the comments using Stream.reduce()
for this purpose is not correct. See Reduction and Mutable Reduction or Java 8 Streams - collect vs reduce for more information.
You can use Java Stream.collect()
instead to generate your list with sums:
List<Long> numbers = Arrays.asList(2L, 2L, 4L, 5L);
List<Pair> results = numbers.stream()
.collect(ArrayList::new, (sums, number) -> {
if (sums.isEmpty()) {
sums.add(new Pair(number, number));
} else {
sums.add(new Pair(number, number + sums.get(sums.size() - 1).getSum()));
}
}, (sums1, sums2) -> {
if (!sums1.isEmpty()) {
long sum = sums1.get(sums1.size() - 1).getSum();
sums2.forEach(p -> p.setSum(p.getSum() + sum));
}
sums1.addAll(sums2);
});
This combines all the numbers and creates a pair for each number with the addition to the previous sum. It uses the following Pair
class as helper:
public class Pair {
private long number;
private long sum;
public Pair(long number, long sum) {
this.number = number;
this.sum = sum;
}
public long getNumber() {
return number;
}
public void setSum(long sum) {
this.sum = sum;
}
public long getSum() {
return sum;
}
}
You can easily change that helper class if you want to add some more information.
The result at the end is:
[
Pair{number=2, sum=2},
Pair{number=2, sum=4},
Pair{number=4, sum=8},
Pair{number=5, sum=13}
]