首页 > Java > java教程 > 正文

Java 数据处理:如何将行数据转换为列数据?

花韻仙語
发布: 2024-11-07 19:27:36
原创
603人浏览过

java 数据处理:如何将行数据转换为列数据?

java 数据处理:实现行转列

问题:

如何将如下源数据:

源数据如下

class    studentid    subject    score
class one    1    english    84
class one    1    math    77
class one    1    pe    69
class one    2    english    81
class one    2    math    80
…    
登录后复制

转换成如下期望输出:

class    studentid    english    math    pe
class one    1    84    77    69
登录后复制

解决方案:

立即学习Java免费学习笔记(深入)”;

行转列操作:

序列猴子开放平台
序列猴子开放平台

具有长序列、多模态、单模型、大数据等特点的超大规模语言模型

序列猴子开放平台 0
查看详情 序列猴子开放平台

为了将数据从行转为列,我们需要使用 java 的“分组”和“聚合”操作。

首先,根据 class 和 studentid 对数据进行分组:

import java.util.hashmap;
import java.util.list;
import java.util.map;
import java.util.stream.collectors;

public class rowtocolumn {

    public static map<string, map<string, list<integer>>> rowtocolumn(list<rowdata> data) {
        return data.stream()
            .collect(collectors.groupingby(r -> r.getclass() + ";" + r.getstudentid(),
                collectors.groupingby(rowdata::getsubject, collectors.mapping(rowdata::getscore, collectors.tolist()))));

    }

    public static class rowdata {
        private string class;
        private string studentid;
        private string subject;
        private integer score;
        // getters and setters
    }

    public static void main(string[] args) {

        // 初始化源数据
        list<rowdata> data = new arraylist<>();

        // ...

        // 执行行转列操作
        map<string, map<string, list<integer>>> result = rowtocolumn(data);

    }
}
登录后复制

然后,我们对每个组聚合 subject 和 score 列,并使用 map 结构来存储结果:

// for each group by CLASS + STUDENTID

// create a new map to store the aggregated data for each SUBJECT

// for each SUBJECT in the group

// get the list of SCORES for the SUBJECT in the group

// add the SUBJECT and the list of SCORES to the map

// return the map
登录后复制

输出的 map 将包含以 class 和 studentid 作为键的行,值为 subject 和 score 的嵌套 map。

通过将行转为列,我们便可以更轻松地访问和处理数据。

以上就是Java 数据处理:如何将行数据转换为列数据?的详细内容,更多请关注php中文网其它相关文章!

相关标签:
最佳 Windows 性能的顶级免费优化软件
最佳 Windows 性能的顶级免费优化软件

每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。

下载
来源:php中文网
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
最新问题
开源免费商场系统广告
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 意见反馈 讲师合作 广告合作 最新更新 English
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送
PHP中文网APP
随时随地碎片化学习

Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号