doubleavgField1=(double)sumField1/dataList.size();doubleavgField2=(double)sumField2/dataList.size();System.out.println("Average of Field1: "+avgField1);System.out.println("Average of Field2: "+avgField2); 1. 2. 3. 4. 5. 状态图 CreateClassCreateListInitListCalculateSumCalculateAverage ...
下面我们以一个更完整的示例来展示如何计算一个整型数组的平均值,并输出结果: importjava.util.*;publicclassMain{publicstaticvoidmain(String[]args){int[]arr={10,20,30,40,50};intsum=0;for(intnum:arr){sum+=num;}doubleaverage=(double)sum/arr.length;System.out.println("数组的平均值为:"+average...
importjava.util.ArrayList;importjava.util.List;publicclassAverageCalculator{publicstaticdoublecalculateAverage(List<Integer> numbers){if(numbers ==null|| numbers.isEmpty()) {thrownewIllegalArgumentException("List of numbers must not be null or empty"); }intsum=0;for(intnumber : numbers) { sum +...
*/publicstaticList<Users>produceUser(){List<Users>usersList=newArrayList<>();for(int i=1;i<=10;i++){Users users=newUsers();users.setId(Long.valueOf(i));users.setName("kobe"+i);users.setAge(15+newRandom().nextInt(5));users.setJobNumber("jobNumber"+i);if(i%2==0){users.set...
Thanks for all of the thought-provoking questions. I now better understand how to get the sum of the values of the ArrayList. However, now I have happened upon a somewhat different problem. In the Tester class, I am trying to print out the average monthly electric bill value. However, wh...
();// 最小值OptionalInt min=list.stream().mapToInt(Pool::getValue).min();// 平均值OptionalDouble average=list.stream().mapToInt(Pool::getValue).average();System.err.println(sum);System.err.println(max.getAsInt());System.err.println(min.getAsInt());System.err.println(average.getAs...
System.out.println(users);//求平均年龄System.out.println(list.stream().mapToInt(Users::getAge).average().getAsDouble());//求最大年龄System.out.println(list.stream().mapToInt(Users::getAge).max().getAsInt()); } 输出结果如下
Once you got the required integer array, just pass it to theaverage(int[] input)method, it returns afloatvalue, which is the average of all numbers in the given array. In this method, we first calculate the sum of all elements and divide the total sum by the length of the array to...
// 求总数Long count=personList.stream().collect(Collectors.counting());// 求平均工资Double average=personList.stream().collect(Collectors.averagingDouble(Person::getSalary));// 求最高工资Optional<Integer>max=personList.stream().map(Person::getSalary).collect(Collectors.maxBy(Integer::compare));/...
(User::getAge).sum(); double aveVal = userList.stream().mapToInt(User::getAge).average().getAsDouble(); //打印结果 System.out.println("最大年龄:" + maxVal); System.out.println("最小年龄:" + minVal); System.out.println("年龄总和:" + sumVal); System.out.println("平均年龄:" ...