
问题:
如何将如下源数据:
源数据如下 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免费学习笔记(深入)”;
行转列操作:
为了将数据从行转为列,我们需要使用 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中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号