网络片 规划技术部 85 5 4 4 4 网络片 规划技术部 95 5 4 5 5 网络片 规划技术部 90 5 4 4 5 网络片 规划技术部 90 5 5 4 4 网络片 规划技术部 90 5 4 5 4 网络片 规划技术部 95 5 5 5 4 网络片 规划技术部 90 5 4 4 5 网络片 规划技术部 95 5 5 5 4 网络片 规划技术部 95 5 5 4 5 网络片 规划技术部 95 5 5 5 4 网络片 规划技术部 95 5 5 5 4 网络片 规划技术部 95 5 4 5 5 网络片 规划技术部 95 5 4 5 5 网络片 规划技术部 85 5 4 4 4 网络片 规划技术部 90 5 5 4 4 网络片 规划技术部 95 5 5 4 5 这个一个sheet页 /** * 导出得分详情的头部标题。 */ private List<List> headTitle;

/**
 * 导出得分详情的sheet名称。
 */
private Collection<String> sheetNames;

/**
 * 导出得分详情的内容。
 */
private Collection<List<List<Object>>> contents;

Java怎么求列和并且取平均值保留四位小数, 不用二维数组和不用for循环,不要写死获取,因为有多个列内容:可以使用Java Stream API来实现求列和并取平均值的功能。首先,将内容转换成Stream对象,然后使用mapToInt方法将每个元素转换为对应列的值,再使用sum方法求和,最后使用average方法求平均值并保留四位小数。

下面是示例代码:

import java.util.Collection;
import java.util.List;

public class ColumnSumAndAverage {
    public static void main(String[] args) {
        // 假设内容为一个Collection<List<List<Object>>>对象
        Collection<List<List<Object>>> contents = getContents();
        
        // 获取第三列的和及平均值
        double sum = getColumnSum(contents, 2);
        double average = getColumnAverage(contents, 2);
        
        // 输出结果
        System.out.println("第三列的和为:" + sum);
        System.out.println("第三列的平均值为:" + average);
    }
    
    // 获取内容
    private static Collection<List<List<Object>>> getContents() {
        // 返回内容的具体实现
    }
    
    // 求指定列的和
    private static double getColumnSum(Collection<List<List<Object>>> contents, int columnIndex) {
        return contents.stream()
                .flatMap(List::stream)
                .mapToInt(list -> (int) list.get(columnIndex))
                .sum();
    }
    
    // 求指定列的平均值
    private static double getColumnAverage(Collection<List<List<Object>>> contents, int columnIndex) {
        return contents.stream()
                .flatMap(List::stream)
                .mapToInt(list -> (int) list.get(columnIndex))
                .average()
                .orElse(0.0); // 如果没有元素,则返回0
    }
}

在示例代码中,假设getContents()方法返回了内容的具体实现。getColumnSum方法和getColumnAverage方法分别使用Stream API对内容进行处理,通过flatMap方法将多维List展平为一维List,然后使用mapToInt方法将每个元素转换为对应列的值,最后使用sum方法求和或使用average方法求平均值。注意,可以根据具体需求来修改方法中的参数类型和返回值类型。


原文地址: https://www.cveoy.top/t/topic/qt2B 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录