Cumulative Sum using Java 8 stream APIIs Java “pass-by-reference” or “pass-by-value”?How do I efficiently iterate over each entry in a Java Map?What is the difference between public, protected, package-private and private in Java?How do I read / convert an InputStream into a String in Java?When to use LinkedList over ArrayList in Java?How do I generate random integers within a specific range in Java?How do I convert a String to an int in Java?Creating a memory leak with JavaJava 8 List<V> into Map<K, V>How to Convert a Java 8 Stream to an Array?

Difference between shutdown options

What's the name of the logical fallacy where a debater extends a statement far beyond the original statement to make it true?

Make a Bowl of Alphabet Soup

Why would five hundred and five be same as one?

Can I run 125khz RF circuit on a breadboard?

How to leave product feedback on macOS?

Can I say "fingers" when referring to toes?

How to get directions in deep space?

How to make a list of partial sums using forEach

Sigmoid with a slope but no asymptotes?

Anime with legendary swords made from talismans and a man who could change them with a shattered body

What should be the ideal length of sentences in a blog post for ease of reading?

What is the meaning of "You've never met a graph you didn't like?"

Isometric embedding of a genus g surface

What is this high flying aircraft over Pennsylvania?

ContourPlot — How do I color by contour curvature?

Storage of electrolytic capacitors - how long?

Deciphering cause of death?

Is there a reason to prefer HFS+ over APFS for disk images in High Sierra and/or Mojave?

What the heck is gets(stdin) on site coderbyte?

Ways of geometrical multiplication

What does the word 'upstream' mean in the context?

How to I force windows to use a specific version of SQLCMD?

Do I have to take mana from my deck or hand when tapping a dual land?



Cumulative Sum using Java 8 stream API


Is Java “pass-by-reference” or “pass-by-value”?How do I efficiently iterate over each entry in a Java Map?What is the difference between public, protected, package-private and private in Java?How do I read / convert an InputStream into a String in Java?When to use LinkedList over ArrayList in Java?How do I generate random integers within a specific range in Java?How do I convert a String to an int in Java?Creating a memory leak with JavaJava 8 List<V> into Map<K, V>How to Convert a Java 8 Stream to an Array?













7















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 Stream API java 8 ?



List<Integer> list1 = new ArrayList<>();
list1.addAll(Arrays.asList(1, 2, 3, 4));
List<Integer> list2 = new ArrayList<>();
// initialization
list2.add(list1.get(0));
for(int i=1;i<list1.size();i++)
// increment step
list2.add(list2.get(i-1) + list1.get(i));



How can I change above imperative style code into declarative one ?



list2 should be [1, 3, 6, 10]









share|improve this question



















  • 11





    You'll notice from the answers that any solution using streams is going to be inefficient. Streams aren't really intended for this use case. (In general, streams aren't intended to replace all imperative code.)

    – Louis Wasserman
    7 hours ago











  • @LouisWasserman I agree. But in this case I do not care about efficiency (probably should have mentioned it in the question). I wanted to write the same thing with something other than above mentioned imperative style. I could not do it myself, as I was stuck because the solution is kind of mixture of map and reduce operation

    – run_time_error
    6 hours ago











  • Man, the lack of tuples really hurts here.

    – Alexander
    1 hour ago















7















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 Stream API java 8 ?



List<Integer> list1 = new ArrayList<>();
list1.addAll(Arrays.asList(1, 2, 3, 4));
List<Integer> list2 = new ArrayList<>();
// initialization
list2.add(list1.get(0));
for(int i=1;i<list1.size();i++)
// increment step
list2.add(list2.get(i-1) + list1.get(i));



How can I change above imperative style code into declarative one ?



list2 should be [1, 3, 6, 10]









share|improve this question



















  • 11





    You'll notice from the answers that any solution using streams is going to be inefficient. Streams aren't really intended for this use case. (In general, streams aren't intended to replace all imperative code.)

    – Louis Wasserman
    7 hours ago











  • @LouisWasserman I agree. But in this case I do not care about efficiency (probably should have mentioned it in the question). I wanted to write the same thing with something other than above mentioned imperative style. I could not do it myself, as I was stuck because the solution is kind of mixture of map and reduce operation

    – run_time_error
    6 hours ago











  • Man, the lack of tuples really hurts here.

    – Alexander
    1 hour ago













7












7








7


2






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 Stream API java 8 ?



List<Integer> list1 = new ArrayList<>();
list1.addAll(Arrays.asList(1, 2, 3, 4));
List<Integer> list2 = new ArrayList<>();
// initialization
list2.add(list1.get(0));
for(int i=1;i<list1.size();i++)
// increment step
list2.add(list2.get(i-1) + list1.get(i));



How can I change above imperative style code into declarative one ?



list2 should be [1, 3, 6, 10]









share|improve this question
















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 Stream API java 8 ?



List<Integer> list1 = new ArrayList<>();
list1.addAll(Arrays.asList(1, 2, 3, 4));
List<Integer> list2 = new ArrayList<>();
// initialization
list2.add(list1.get(0));
for(int i=1;i<list1.size();i++)
// increment step
list2.add(list2.get(i-1) + list1.get(i));



How can I change above imperative style code into declarative one ?



list2 should be [1, 3, 6, 10]






java java-8 java-stream






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited 7 hours ago









Stefan Zobel

2,47231931




2,47231931










asked 7 hours ago









run_time_errorrun_time_error

151211




151211







  • 11





    You'll notice from the answers that any solution using streams is going to be inefficient. Streams aren't really intended for this use case. (In general, streams aren't intended to replace all imperative code.)

    – Louis Wasserman
    7 hours ago











  • @LouisWasserman I agree. But in this case I do not care about efficiency (probably should have mentioned it in the question). I wanted to write the same thing with something other than above mentioned imperative style. I could not do it myself, as I was stuck because the solution is kind of mixture of map and reduce operation

    – run_time_error
    6 hours ago











  • Man, the lack of tuples really hurts here.

    – Alexander
    1 hour ago












  • 11





    You'll notice from the answers that any solution using streams is going to be inefficient. Streams aren't really intended for this use case. (In general, streams aren't intended to replace all imperative code.)

    – Louis Wasserman
    7 hours ago











  • @LouisWasserman I agree. But in this case I do not care about efficiency (probably should have mentioned it in the question). I wanted to write the same thing with something other than above mentioned imperative style. I could not do it myself, as I was stuck because the solution is kind of mixture of map and reduce operation

    – run_time_error
    6 hours ago











  • Man, the lack of tuples really hurts here.

    – Alexander
    1 hour ago







11




11





You'll notice from the answers that any solution using streams is going to be inefficient. Streams aren't really intended for this use case. (In general, streams aren't intended to replace all imperative code.)

– Louis Wasserman
7 hours ago





You'll notice from the answers that any solution using streams is going to be inefficient. Streams aren't really intended for this use case. (In general, streams aren't intended to replace all imperative code.)

– Louis Wasserman
7 hours ago













@LouisWasserman I agree. But in this case I do not care about efficiency (probably should have mentioned it in the question). I wanted to write the same thing with something other than above mentioned imperative style. I could not do it myself, as I was stuck because the solution is kind of mixture of map and reduce operation

– run_time_error
6 hours ago





@LouisWasserman I agree. But in this case I do not care about efficiency (probably should have mentioned it in the question). I wanted to write the same thing with something other than above mentioned imperative style. I could not do it myself, as I was stuck because the solution is kind of mixture of map and reduce operation

– run_time_error
6 hours ago













Man, the lack of tuples really hurts here.

– Alexander
1 hour ago





Man, the lack of tuples really hurts here.

– Alexander
1 hour ago












5 Answers
5






active

oldest

votes


















4














Streams are not suited for this kind of task, as there is state involved (the cumulative partial sum). Instead, you could use Arrays.parallelPrefix:



Integer[] arr = list1.toArray(Integer[]::new);

Arrays.parallelPrefix(arr, Integer::sum);

List<Integer> list2 = Arrays.asList(arr);


This first copies list1 to an array by using Collection.toArray, which is available since JDK 11. If you are not on Java 11 yet, you could replace the first line with the traditional toArray call:



Integer[] arr = list1.toArray(new Integer[list1.size()]);


This solution doesn't use streams, yet it's declarative, because Arrays.parallelPrefix receives the cumulative operation as an argument (Integer::sum in this case).



Time complexity is O(N), though there might be some not-minor constant costs involved associated with setting up the infrastructure needed for parallel processing. However, according to the docs:




Parallel prefix computation is usually more efficient than sequential loops for large arrays




So it seems it's worth giving this approach a try.






share|improve this answer




















  • 1





    Never heard of parallel prefix. thank you very much for teaching me a new concept. :). I will definitely give a try.

    – run_time_error
    6 hours ago











  • @run_time_error Here's more reading about the subject.

    – Federico Peralta Schaffner
    5 hours ago


















3














For every index: iterate from zero to that index, get each element, and get the sum

Box the ints to Integers

Collect to a list



IntStream.range(0, list1.size())
.map(i -> IntStream.rangeClosed(0, i).map(list1::get).sum())
.boxed()
.collect(Collectors.toList());


You're adding every number together every time, rather than reusing the previous cumulative result, but streams do not lend themselves to looking at results from previous iterations.



You could write your own collector but at this point, honestly why are you even bothering with streams?



list1.stream()
.collect(
Collector.of(
ArrayList::new,
(a, b) -> a.add(a.isEmpty() ? b : b + a.get(a.size() - 1)),
(a, b) -> throw new UnsupportedOperationException();
)
);





share|improve this answer




















  • 5





    That's O(n^2) !! (as opposed to the O(n) of the OP)

    – DodgyCodeException
    7 hours ago







  • 1





    @DodgyCodeException Yes.

    – Michael
    7 hours ago











  • @Michael thanks for your elaborate response. I have learnt that I can write my own collector. I know this is overkill. But good to know that there are other ways.

    – run_time_error
    6 hours ago


















2














An O(n) solution would be the following, but I don't find it very elegant. I guess it is a matter of taste



AtomicInteger ai = new AtomicInteger();
List<Integer> collect = list1.stream().map(ai::addAndGet)
.collect(Collectors.toList());
System.out.println(collect); // [1, 3, 6, 10]





share|improve this answer


















  • 3





    This solution only works as long as the stream is sequential. Parallelising it would break this completely.

    – Ben R.
    6 hours ago


















1














You can use sublist to sum up until the current index from start:



List<Integer> list = IntStream.range(0, list1.size())
.mapToObj(i -> list1.subList(0, i + 1).stream().mapToInt(Integer::intValue).sum())
.collect(Collectors.toList());





share|improve this answer




















  • 4





    can also be mapToInt(Integer::intValue)

    – Sharon Ben Asher
    7 hours ago


















1














You can just use Stream.collect() for that:



List<Integer> list1 = Arrays.asList(1, 2, 3, 4);
List<Integer> 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]






share|improve this answer
























    Your Answer






    StackExchange.ifUsing("editor", function ()
    StackExchange.using("externalEditor", function ()
    StackExchange.using("snippets", function ()
    StackExchange.snippets.init();
    );
    );
    , "code-snippets");

    StackExchange.ready(function()
    var channelOptions =
    tags: "".split(" "),
    id: "1"
    ;
    initTagRenderer("".split(" "), "".split(" "), channelOptions);

    StackExchange.using("externalEditor", function()
    // Have to fire editor after snippets, if snippets enabled
    if (StackExchange.settings.snippets.snippetsEnabled)
    StackExchange.using("snippets", function()
    createEditor();
    );

    else
    createEditor();

    );

    function createEditor()
    StackExchange.prepareEditor(
    heartbeatType: 'answer',
    autoActivateHeartbeat: false,
    convertImagesToLinks: true,
    noModals: true,
    showLowRepImageUploadWarning: true,
    reputationToPostImages: 10,
    bindNavPrevention: true,
    postfix: "",
    imageUploader:
    brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
    contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
    allowUrls: true
    ,
    onDemand: true,
    discardSelector: ".discard-answer"
    ,immediatelyShowMarkdownHelp:true
    );



    );













    draft saved

    draft discarded


















    StackExchange.ready(
    function ()
    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55265797%2fcumulative-sum-using-java-8-stream-api%23new-answer', 'question_page');

    );

    Post as a guest















    Required, but never shown

























    5 Answers
    5






    active

    oldest

    votes








    5 Answers
    5






    active

    oldest

    votes









    active

    oldest

    votes






    active

    oldest

    votes









    4














    Streams are not suited for this kind of task, as there is state involved (the cumulative partial sum). Instead, you could use Arrays.parallelPrefix:



    Integer[] arr = list1.toArray(Integer[]::new);

    Arrays.parallelPrefix(arr, Integer::sum);

    List<Integer> list2 = Arrays.asList(arr);


    This first copies list1 to an array by using Collection.toArray, which is available since JDK 11. If you are not on Java 11 yet, you could replace the first line with the traditional toArray call:



    Integer[] arr = list1.toArray(new Integer[list1.size()]);


    This solution doesn't use streams, yet it's declarative, because Arrays.parallelPrefix receives the cumulative operation as an argument (Integer::sum in this case).



    Time complexity is O(N), though there might be some not-minor constant costs involved associated with setting up the infrastructure needed for parallel processing. However, according to the docs:




    Parallel prefix computation is usually more efficient than sequential loops for large arrays




    So it seems it's worth giving this approach a try.






    share|improve this answer




















    • 1





      Never heard of parallel prefix. thank you very much for teaching me a new concept. :). I will definitely give a try.

      – run_time_error
      6 hours ago











    • @run_time_error Here's more reading about the subject.

      – Federico Peralta Schaffner
      5 hours ago















    4














    Streams are not suited for this kind of task, as there is state involved (the cumulative partial sum). Instead, you could use Arrays.parallelPrefix:



    Integer[] arr = list1.toArray(Integer[]::new);

    Arrays.parallelPrefix(arr, Integer::sum);

    List<Integer> list2 = Arrays.asList(arr);


    This first copies list1 to an array by using Collection.toArray, which is available since JDK 11. If you are not on Java 11 yet, you could replace the first line with the traditional toArray call:



    Integer[] arr = list1.toArray(new Integer[list1.size()]);


    This solution doesn't use streams, yet it's declarative, because Arrays.parallelPrefix receives the cumulative operation as an argument (Integer::sum in this case).



    Time complexity is O(N), though there might be some not-minor constant costs involved associated with setting up the infrastructure needed for parallel processing. However, according to the docs:




    Parallel prefix computation is usually more efficient than sequential loops for large arrays




    So it seems it's worth giving this approach a try.






    share|improve this answer




















    • 1





      Never heard of parallel prefix. thank you very much for teaching me a new concept. :). I will definitely give a try.

      – run_time_error
      6 hours ago











    • @run_time_error Here's more reading about the subject.

      – Federico Peralta Schaffner
      5 hours ago













    4












    4








    4







    Streams are not suited for this kind of task, as there is state involved (the cumulative partial sum). Instead, you could use Arrays.parallelPrefix:



    Integer[] arr = list1.toArray(Integer[]::new);

    Arrays.parallelPrefix(arr, Integer::sum);

    List<Integer> list2 = Arrays.asList(arr);


    This first copies list1 to an array by using Collection.toArray, which is available since JDK 11. If you are not on Java 11 yet, you could replace the first line with the traditional toArray call:



    Integer[] arr = list1.toArray(new Integer[list1.size()]);


    This solution doesn't use streams, yet it's declarative, because Arrays.parallelPrefix receives the cumulative operation as an argument (Integer::sum in this case).



    Time complexity is O(N), though there might be some not-minor constant costs involved associated with setting up the infrastructure needed for parallel processing. However, according to the docs:




    Parallel prefix computation is usually more efficient than sequential loops for large arrays




    So it seems it's worth giving this approach a try.






    share|improve this answer















    Streams are not suited for this kind of task, as there is state involved (the cumulative partial sum). Instead, you could use Arrays.parallelPrefix:



    Integer[] arr = list1.toArray(Integer[]::new);

    Arrays.parallelPrefix(arr, Integer::sum);

    List<Integer> list2 = Arrays.asList(arr);


    This first copies list1 to an array by using Collection.toArray, which is available since JDK 11. If you are not on Java 11 yet, you could replace the first line with the traditional toArray call:



    Integer[] arr = list1.toArray(new Integer[list1.size()]);


    This solution doesn't use streams, yet it's declarative, because Arrays.parallelPrefix receives the cumulative operation as an argument (Integer::sum in this case).



    Time complexity is O(N), though there might be some not-minor constant costs involved associated with setting up the infrastructure needed for parallel processing. However, according to the docs:




    Parallel prefix computation is usually more efficient than sequential loops for large arrays




    So it seems it's worth giving this approach a try.







    share|improve this answer














    share|improve this answer



    share|improve this answer








    edited 6 hours ago

























    answered 7 hours ago









    Federico Peralta SchaffnerFederico Peralta Schaffner

    23.6k43778




    23.6k43778







    • 1





      Never heard of parallel prefix. thank you very much for teaching me a new concept. :). I will definitely give a try.

      – run_time_error
      6 hours ago











    • @run_time_error Here's more reading about the subject.

      – Federico Peralta Schaffner
      5 hours ago












    • 1





      Never heard of parallel prefix. thank you very much for teaching me a new concept. :). I will definitely give a try.

      – run_time_error
      6 hours ago











    • @run_time_error Here's more reading about the subject.

      – Federico Peralta Schaffner
      5 hours ago







    1




    1





    Never heard of parallel prefix. thank you very much for teaching me a new concept. :). I will definitely give a try.

    – run_time_error
    6 hours ago





    Never heard of parallel prefix. thank you very much for teaching me a new concept. :). I will definitely give a try.

    – run_time_error
    6 hours ago













    @run_time_error Here's more reading about the subject.

    – Federico Peralta Schaffner
    5 hours ago





    @run_time_error Here's more reading about the subject.

    – Federico Peralta Schaffner
    5 hours ago













    3














    For every index: iterate from zero to that index, get each element, and get the sum

    Box the ints to Integers

    Collect to a list



    IntStream.range(0, list1.size())
    .map(i -> IntStream.rangeClosed(0, i).map(list1::get).sum())
    .boxed()
    .collect(Collectors.toList());


    You're adding every number together every time, rather than reusing the previous cumulative result, but streams do not lend themselves to looking at results from previous iterations.



    You could write your own collector but at this point, honestly why are you even bothering with streams?



    list1.stream()
    .collect(
    Collector.of(
    ArrayList::new,
    (a, b) -> a.add(a.isEmpty() ? b : b + a.get(a.size() - 1)),
    (a, b) -> throw new UnsupportedOperationException();
    )
    );





    share|improve this answer




















    • 5





      That's O(n^2) !! (as opposed to the O(n) of the OP)

      – DodgyCodeException
      7 hours ago







    • 1





      @DodgyCodeException Yes.

      – Michael
      7 hours ago











    • @Michael thanks for your elaborate response. I have learnt that I can write my own collector. I know this is overkill. But good to know that there are other ways.

      – run_time_error
      6 hours ago















    3














    For every index: iterate from zero to that index, get each element, and get the sum

    Box the ints to Integers

    Collect to a list



    IntStream.range(0, list1.size())
    .map(i -> IntStream.rangeClosed(0, i).map(list1::get).sum())
    .boxed()
    .collect(Collectors.toList());


    You're adding every number together every time, rather than reusing the previous cumulative result, but streams do not lend themselves to looking at results from previous iterations.



    You could write your own collector but at this point, honestly why are you even bothering with streams?



    list1.stream()
    .collect(
    Collector.of(
    ArrayList::new,
    (a, b) -> a.add(a.isEmpty() ? b : b + a.get(a.size() - 1)),
    (a, b) -> throw new UnsupportedOperationException();
    )
    );





    share|improve this answer




















    • 5





      That's O(n^2) !! (as opposed to the O(n) of the OP)

      – DodgyCodeException
      7 hours ago







    • 1





      @DodgyCodeException Yes.

      – Michael
      7 hours ago











    • @Michael thanks for your elaborate response. I have learnt that I can write my own collector. I know this is overkill. But good to know that there are other ways.

      – run_time_error
      6 hours ago













    3












    3








    3







    For every index: iterate from zero to that index, get each element, and get the sum

    Box the ints to Integers

    Collect to a list



    IntStream.range(0, list1.size())
    .map(i -> IntStream.rangeClosed(0, i).map(list1::get).sum())
    .boxed()
    .collect(Collectors.toList());


    You're adding every number together every time, rather than reusing the previous cumulative result, but streams do not lend themselves to looking at results from previous iterations.



    You could write your own collector but at this point, honestly why are you even bothering with streams?



    list1.stream()
    .collect(
    Collector.of(
    ArrayList::new,
    (a, b) -> a.add(a.isEmpty() ? b : b + a.get(a.size() - 1)),
    (a, b) -> throw new UnsupportedOperationException();
    )
    );





    share|improve this answer















    For every index: iterate from zero to that index, get each element, and get the sum

    Box the ints to Integers

    Collect to a list



    IntStream.range(0, list1.size())
    .map(i -> IntStream.rangeClosed(0, i).map(list1::get).sum())
    .boxed()
    .collect(Collectors.toList());


    You're adding every number together every time, rather than reusing the previous cumulative result, but streams do not lend themselves to looking at results from previous iterations.



    You could write your own collector but at this point, honestly why are you even bothering with streams?



    list1.stream()
    .collect(
    Collector.of(
    ArrayList::new,
    (a, b) -> a.add(a.isEmpty() ? b : b + a.get(a.size() - 1)),
    (a, b) -> throw new UnsupportedOperationException();
    )
    );






    share|improve this answer














    share|improve this answer



    share|improve this answer








    edited 7 hours ago

























    answered 7 hours ago









    MichaelMichael

    21.1k83572




    21.1k83572







    • 5





      That's O(n^2) !! (as opposed to the O(n) of the OP)

      – DodgyCodeException
      7 hours ago







    • 1





      @DodgyCodeException Yes.

      – Michael
      7 hours ago











    • @Michael thanks for your elaborate response. I have learnt that I can write my own collector. I know this is overkill. But good to know that there are other ways.

      – run_time_error
      6 hours ago












    • 5





      That's O(n^2) !! (as opposed to the O(n) of the OP)

      – DodgyCodeException
      7 hours ago







    • 1





      @DodgyCodeException Yes.

      – Michael
      7 hours ago











    • @Michael thanks for your elaborate response. I have learnt that I can write my own collector. I know this is overkill. But good to know that there are other ways.

      – run_time_error
      6 hours ago







    5




    5





    That's O(n^2) !! (as opposed to the O(n) of the OP)

    – DodgyCodeException
    7 hours ago






    That's O(n^2) !! (as opposed to the O(n) of the OP)

    – DodgyCodeException
    7 hours ago





    1




    1





    @DodgyCodeException Yes.

    – Michael
    7 hours ago





    @DodgyCodeException Yes.

    – Michael
    7 hours ago













    @Michael thanks for your elaborate response. I have learnt that I can write my own collector. I know this is overkill. But good to know that there are other ways.

    – run_time_error
    6 hours ago





    @Michael thanks for your elaborate response. I have learnt that I can write my own collector. I know this is overkill. But good to know that there are other ways.

    – run_time_error
    6 hours ago











    2














    An O(n) solution would be the following, but I don't find it very elegant. I guess it is a matter of taste



    AtomicInteger ai = new AtomicInteger();
    List<Integer> collect = list1.stream().map(ai::addAndGet)
    .collect(Collectors.toList());
    System.out.println(collect); // [1, 3, 6, 10]





    share|improve this answer


















    • 3





      This solution only works as long as the stream is sequential. Parallelising it would break this completely.

      – Ben R.
      6 hours ago















    2














    An O(n) solution would be the following, but I don't find it very elegant. I guess it is a matter of taste



    AtomicInteger ai = new AtomicInteger();
    List<Integer> collect = list1.stream().map(ai::addAndGet)
    .collect(Collectors.toList());
    System.out.println(collect); // [1, 3, 6, 10]





    share|improve this answer


















    • 3





      This solution only works as long as the stream is sequential. Parallelising it would break this completely.

      – Ben R.
      6 hours ago













    2












    2








    2







    An O(n) solution would be the following, but I don't find it very elegant. I guess it is a matter of taste



    AtomicInteger ai = new AtomicInteger();
    List<Integer> collect = list1.stream().map(ai::addAndGet)
    .collect(Collectors.toList());
    System.out.println(collect); // [1, 3, 6, 10]





    share|improve this answer













    An O(n) solution would be the following, but I don't find it very elegant. I guess it is a matter of taste



    AtomicInteger ai = new AtomicInteger();
    List<Integer> collect = list1.stream().map(ai::addAndGet)
    .collect(Collectors.toList());
    System.out.println(collect); // [1, 3, 6, 10]






    share|improve this answer












    share|improve this answer



    share|improve this answer










    answered 7 hours ago









    Yassin HajajYassin Hajaj

    14.2k72961




    14.2k72961







    • 3





      This solution only works as long as the stream is sequential. Parallelising it would break this completely.

      – Ben R.
      6 hours ago












    • 3





      This solution only works as long as the stream is sequential. Parallelising it would break this completely.

      – Ben R.
      6 hours ago







    3




    3





    This solution only works as long as the stream is sequential. Parallelising it would break this completely.

    – Ben R.
    6 hours ago





    This solution only works as long as the stream is sequential. Parallelising it would break this completely.

    – Ben R.
    6 hours ago











    1














    You can use sublist to sum up until the current index from start:



    List<Integer> list = IntStream.range(0, list1.size())
    .mapToObj(i -> list1.subList(0, i + 1).stream().mapToInt(Integer::intValue).sum())
    .collect(Collectors.toList());





    share|improve this answer




















    • 4





      can also be mapToInt(Integer::intValue)

      – Sharon Ben Asher
      7 hours ago















    1














    You can use sublist to sum up until the current index from start:



    List<Integer> list = IntStream.range(0, list1.size())
    .mapToObj(i -> list1.subList(0, i + 1).stream().mapToInt(Integer::intValue).sum())
    .collect(Collectors.toList());





    share|improve this answer




















    • 4





      can also be mapToInt(Integer::intValue)

      – Sharon Ben Asher
      7 hours ago













    1












    1








    1







    You can use sublist to sum up until the current index from start:



    List<Integer> list = IntStream.range(0, list1.size())
    .mapToObj(i -> list1.subList(0, i + 1).stream().mapToInt(Integer::intValue).sum())
    .collect(Collectors.toList());





    share|improve this answer















    You can use sublist to sum up until the current index from start:



    List<Integer> list = IntStream.range(0, list1.size())
    .mapToObj(i -> list1.subList(0, i + 1).stream().mapToInt(Integer::intValue).sum())
    .collect(Collectors.toList());






    share|improve this answer














    share|improve this answer



    share|improve this answer








    edited 7 hours ago

























    answered 7 hours ago









    RuslanRuslan

    3,8461027




    3,8461027







    • 4





      can also be mapToInt(Integer::intValue)

      – Sharon Ben Asher
      7 hours ago












    • 4





      can also be mapToInt(Integer::intValue)

      – Sharon Ben Asher
      7 hours ago







    4




    4





    can also be mapToInt(Integer::intValue)

    – Sharon Ben Asher
    7 hours ago





    can also be mapToInt(Integer::intValue)

    – Sharon Ben Asher
    7 hours ago











    1














    You can just use Stream.collect() for that:



    List<Integer> list1 = Arrays.asList(1, 2, 3, 4);
    List<Integer> 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]






    share|improve this answer





























      1














      You can just use Stream.collect() for that:



      List<Integer> list1 = Arrays.asList(1, 2, 3, 4);
      List<Integer> 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]






      share|improve this answer



























        1












        1








        1







        You can just use Stream.collect() for that:



        List<Integer> list1 = Arrays.asList(1, 2, 3, 4);
        List<Integer> 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]






        share|improve this answer















        You can just use Stream.collect() for that:



        List<Integer> list1 = Arrays.asList(1, 2, 3, 4);
        List<Integer> 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]







        share|improve this answer














        share|improve this answer



        share|improve this answer








        edited 5 hours ago

























        answered 6 hours ago









        Samuel PhilippSamuel Philipp

        2,5321624




        2,5321624



























            draft saved

            draft discarded
















































            Thanks for contributing an answer to Stack Overflow!


            • Please be sure to answer the question. Provide details and share your research!

            But avoid


            • Asking for help, clarification, or responding to other answers.

            • Making statements based on opinion; back them up with references or personal experience.

            To learn more, see our tips on writing great answers.




            draft saved


            draft discarded














            StackExchange.ready(
            function ()
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55265797%2fcumulative-sum-using-java-8-stream-api%23new-answer', 'question_page');

            );

            Post as a guest















            Required, but never shown





















































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown

































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown







            Popular posts from this blog

            How to create a command for the “strange m” symbol in latex? Announcing the arrival of Valued Associate #679: Cesar Manara Planned maintenance scheduled April 23, 2019 at 23:30 UTC (7:30pm US/Eastern)How do you make your own symbol when Detexify fails?Writing bold small caps with mathpazo packageplus-minus symbol with parenthesis around the minus signGreek character in Beamer document titleHow to create dashed right arrow over symbol?Currency symbol: Turkish LiraDouble prec as a single symbol?Plus Sign Too Big; How to Call adfbullet?Is there a TeX macro for three-legged pi?How do I get my integral-like symbol to align like the integral?How to selectively substitute a letter with another symbol representing the same letterHow do I generate a less than symbol and vertical bar that are the same height?

            Българска екзархия Съдържание История | Български екзарси | Вижте също | Външни препратки | Литература | Бележки | НавигацияУстав за управлението на българската екзархия. Цариград, 1870Слово на Ловешкия митрополит Иларион при откриването на Българския народен събор в Цариград на 23. II. 1870 г.Българската правда и гръцката кривда. От С. М. (= Софийски Мелетий). Цариград, 1872Предстоятели на Българската екзархияПодмененият ВеликденИнформационна агенция „Фокус“Димитър Ризов. Българите в техните исторически, етнографически и политически граници (Атлас съдържащ 40 карти). Berlin, Königliche Hoflithographie, Hof-Buch- und -Steindruckerei Wilhelm Greve, 1917Report of the International Commission to Inquire into the Causes and Conduct of the Balkan Wars

            Чепеларе Съдържание География | История | Население | Спортни и природни забележителности | Културни и исторически обекти | Религии | Обществени институции | Известни личности | Редовни събития | Галерия | Източници | Литература | Външни препратки | Навигация41°43′23.99″ с. ш. 24°41′09.99″ и. д. / 41.723333° с. ш. 24.686111° и. д.*ЧепелареЧепеларски Linux fest 2002Начало на Зимен сезон 2005/06Национални хайдушки празници „Капитан Петко Войвода“Град ЧепелареЧепеларе – народният ски курортbgrod.orgwww.terranatura.hit.bgСправка за населението на гр. Исперих, общ. Исперих, обл. РазградМузей на родопския карстМузей на спорта и скитеЧепеларебългарскибългарскианглийскитукИстория на градаСки писти в ЧепелареВремето в ЧепелареРадио и телевизия в ЧепелареЧепеларе мами с родопски чар и добри пистиЕвтин туризъм и снежни атракции в ЧепелареМестоположениеИнформация и снимки от музея на родопския карст3D панорами от ЧепелареЧепелареррр