I have a List of Integer say list1, and I want to get another list list2 which will contain the cumulative sum up until the current index from start. How can I do this using Str
You can just use Stream.collect() for that:
List list1 = Arrays.asList(1, 2, 3, 4);
List list2 = list1.stream()
.collect(ArrayList::new, (sums, number) -> {
if (sums.isEmpty()) {
sums.add(number);
} else {
sums.add(sums.get(sums.size() - 1) + number);
}
}, (sums1, sums2) -> {
if (!sums1.isEmpty()) {
int sum = sums1.get(sums1.size() - 1);
sums2.replaceAll(num -> sum + num);
}
sums1.addAll(sums2);
});
This solution also works for parallel streams. Use list1.parallelStream()
or list1.stream().parallel()
instead of list1.stream()
.
The result in both cases is: [1, 3, 6, 10]