Java-使用POJO将CSV加载到复杂的嵌套地图 [英] Java - Load CSV to Complex Nested Map with POJO
问题描述
我有以下格式的CSV文件
I have CSV file which is in the form as below
student, year, subject, score1, score2, score3
Alex, 2010, Math, 23, 56, 43
Alex, 2011, Science, 45, 32, 45
Matt, 2009, Art, 34, 56, 75
Matt, 2010, Math, 43, 54, 54
我正在尝试找到一种最佳解决方案,以读取CSV文件并将其加载到地图中以进行查找,即Map<String, Map<String, List<SubjectScore>>>
.第一个字符串键用于学生,下一个字符串键用于年份.
I'm trying to find an optimal solution to read the CSV file and load it to a map for lookup purposes i.e. Map<String, Map<String, List<SubjectScore>>>
. The first string key is for student, the next string key is for year.
class SubjectScore {
private String subject;
private int score1;
private int score2;
private int score3;
}
如果有更好的方法存储CSV结构以根据学生和年份信息获取SubjectScore,我想知道这一点.
If there is a better way to store the CSV structure to get SubjectScore based on student and year information, I'll like to know that.
推荐答案
您可以向SubjectStore
添加一些构造函数,并使用流读取文件内容并将其转换为所需的数据结构:
You can add some constructors to SubjectStore
and use streams to read the file contents and convert it to your required data structure:
public class SubjectScore {
private final String subject;
private final int score1;
private final int score2;
private final int score3;
SubjectScore(String subject, int s1, int s2, int s3) {
this.subject = subject;
this.score1 = s1;
this.score2 = s2;
this.score3 = s3;
}
SubjectScore(String subject, String s1, String s2, String s3) {
this(subject, Integer.parseInt(s1), Integer.parseInt(s2), Integer.parseInt(s3));
}
// getters/toString
}
Map<String, Map<String, List<SubjectScore>>> res = Files.lines(Path.of("data.csv"))
.skip(1) // skip header line
.map(line -> line.split("\\s*,\\s*")) // get columns
.collect(
Collectors.groupingBy(arr -> arr[0], TreeMap::new, // key: student
Collectors.groupingBy(arr -> arr[1], TreeMap::new, // key: year
Collectors.mapping(arr -> new SubjectScore(arr[2], arr[3], arr[4], arr[5]), Collectors.toList())
)));
这篇关于Java-使用POJO将CSV加载到复杂的嵌套地图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!