0

For example there is a class similar to this:

class NameBudget {
  String name;
  Integer budget;
}

I am getting the list of budgets using the streams:

listOfNameBudgets.stream().map(NameBudget::getBudget()).collect(Collectors.toList())

How can I get the cumulative budget for each entry of the list using streams?

I am avoiding to first create a list of budget and then do the cumulative. It should be possible to do it while creating the list from an object.

If the list was:

[ {
  "name":"A"
  "budget":1
},
{
  "name":"B"
  "budget":2
},{
  "name":"C"
  "budget":5
}
]

the output list would be [1, 3, 8]

Stefan Zobel
  • 3,182
  • 7
  • 28
  • 38
Himanshu Yadav
  • 13,315
  • 46
  • 162
  • 291
  • The question is for the list of Integers, not the objects. I don't want extract the list of `budget` first and then do the cumulative.I would appreciate if you have the solution or not mark it as a duplicate. – Himanshu Yadav Apr 03 '18 at 16:52
  • 3
    The duplicate is about IntStream. You have a Stream. So you just need a way to transform a Stream into an IntStream. The javadoc is your friend: https://docs.oracle.com/javase/8/docs/api/java/util/stream/Stream.html#mapToInt-java.util.function.ToIntFunction- – JB Nizet Apr 03 '18 at 17:09
  • 2
    There's no real reason to use streams: `int sum = 0; for (NameBudget n : list) { list.add(sum += n.getBudget()); }`. – Andy Turner Apr 03 '18 at 17:16
  • @AndyTurner 1) Composition, 2) parallel friendly, 3) higher level of abstraction – Ousmane D. Apr 03 '18 at 17:28
  • 4
    @Aomine 1) simple code. No need for 2). – Andy Turner Apr 03 '18 at 17:43
  • @Aominè plz don't :) I am already fighting this higher level of abstraction in code review way too much... – Eugene Apr 03 '18 at 18:51
  • @Eugene depends on what “level of abstraction” you’re seeing in code review. :) – Ousmane D. Apr 03 '18 at 18:55

0 Answers0