0

I have an arraylist with the following numbers added to it.

ArrayList<Integer> nums  = new ArrayList<>();

nums.add(4);
nums.add(19);
nums.add(32);
nums.add(-8);

Then I am using the following code to iterate through the list and sum them before printing.

sum += IntStream.range(0, nums.size()).sum();
System.out.println(sum);

It is printing out a value of 6. Does anyone know what is happening or can someone explain what I am doing wrong here? Thank you for your time and if there is anything I can add for clarification, please don't hesitate.

DougM
  • 920
  • 1
  • 9
  • 21

1 Answers1

1

In case of IntStream.range(0,6) you will get values 0,1, 2,3,4,5,6. You need to use nums.stream() to sum your integers in ArrayList

Blockquote

import java.io.*; 
import java.util.*; 
import java.util.*; 
import java.util.stream.IntStream; 

public class HelloWorld{

     public static void main(String []args){
       ArrayList<Integer> nums  = new ArrayList<>();
        nums.add(4);
        nums.add(19);
        nums.add(32);
        nums.add(-8);

        Integer sum = nums.stream()
            .mapToInt(Integer::intValue)
            .sum();
        System.out.println(sum);
     }
}
DadyByte
  • 894
  • 6
  • 18
  • 30
  • 4
    A full code dump with no explanation of what you changed or why is not especially useful, as it forces readers to scan both the original code and your code in order to spot the differences. – VGR Feb 08 '20 at 05:39
  • 1
    @VGR I was about to but, the post got closed so i felt noneed of answering it – DadyByte Feb 08 '20 at 06:20