Home > database >  java 8 summing up a list of integer
java 8 summing up a list of integer

Time:06-23

code

public static int simpleArraySum(List<Integer> ar) {
    int sum = 0;
    for (int i = 0; i < ar.length; i  ) {
        sum = sum   ar[i];
    }
    return sum;
}

where i believe the issue is

how would I iterate through List<Integer> type is different a int[] ar

Error

Solution.java:28: error: cannot find symbol
        for (int i = 0; i < ar.length; i  ) {
                              ^ 
  
symbol:   variable length
  location: variable ar of type List<Integer>

Solution.java:29: error: array required, but List<Integer> found
            sum = sum   ar[i];
                      ^ 

2 errors

what I tried:

After changing ar.length to ar.size() I still have error

Solution.java:26: error: array required, but List<Integer> found
        sum = sum   ar[i];
                      ^
1 error

CodePudding user response:

First, you need to use get to retrieve a value from a list (which is not an array)

  • change length to size
  • use get to fetch the value at index i
public static int simpleListSum(List<Integer> ar) {
    int sum = 0;
    for (int i = 0; i < ar.size(); i  ) {
        sum = sum   ar.get(i);
    }
    return sum;
}

But you can also do it using the enhanced for loop with no index. This also works for arrays.

public static int simpleListSum(List<Integer> ar) {
    int sum = 0;
    for (int val : ar) {
       sum  = val;
    }
    return sum;
}


  •  Tags:  
  • java
  • Related