Here's how you sum a Collection using java 8:
import java.util.ArrayList;
import java.util.List;
public class Solution {
public static void main(String args[]) throws Exception {
List<Integer> numbers = new ArrayList<>();
numbers.add(1);
numbers.add(3);
numbers.add(5);
System.out.println(numbers.stream().mapToInt(value -> value).sum());
}
}
In your code, you would do this to the grade
list. You can set this to gradetotal
after your loop.
value -> value
is saying "take each argument and return it". stream()
returns a Stream
which doesn't have sum()
. mapToInt
returns an IntStream
which does have sum()
. That value -> value
tells the code how to convert each element in the Stream
into an Integer
. Because each element is already an Integer
, we merely have to return each element.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…