课程: Java Practice: Collections

Solution: Calculate average in list - Java教程

课程: Java Practice: Collections

Solution: Calculate average in list

- [Instructor] Here is a solution for solving this problem. So what we want to do is get the average value, or mean, of the source list that's passed in. So I'm going to start by doing some checking to make sure that source is neither null nor empty. If you skip this part, that's fine. So we'll check to see if it's null or if it's empty. And if so, we'll return zero. So going forward, we know we're not going to, for example, try to divide by zero or something. So I'm going to change my return statement at the bottom now to source.stream. And then I'm going to take all the numbers and combine them using the reduce method. So I'm going to start with zero. And then for my accumulator, I'm going to pass in the method integer sum. So integer, then two colons, and sum, and that's going to grab the sum of all the numbers inside of my list. So all I need to do from here is to divide by the size of my source list. So when you're doing that, you could just put source.size, but one thing you'll run into, since source.size is a whole number, that your result will actually be a whole number. So it shows 12 right here. What we have to do is cast source.size to a double, and then test the code again, and then that will actually apply the double math and give us a floating point number rather than a whole number with a decimal in it. So using the stream and the reduced method is one way to get the average of a list of numbers.

内容