我有一个List<report>在Java的,我想将其更改为List<graph>
万一
class report {
String date;
String type;
String count;
}
class graph{
String date;
String numberA;
String numberB;
String numberC;
}
Run Code Online (Sandbox Code Playgroud)
例如我有:
date type count change it into > date numberA numberB numberC
03/21 A 8017 03/21 8017 5019 0
03/21 B 5019 03/22 5001 0 8870
03/22 A 5001 03/23 0 8305 0
03/22 C 8870 03/24 1552 2351 8221
03/23 B 8305
03/24 A 1552
03/24 B 2351
03/24 C 8221
Run Code Online (Sandbox Code Playgroud)
我知道有一些if(条件)和迭代它是可能的但是有另一种解决方案吗?
任何答案将不胜感激.
您希望Graph每个日期有一个实例.因此,将Graph实例存储到Map中,该映射Graph每个日期保留一个.迭代报告列表并在实例进入时构建Graph(numberA,numberB,numberC)的内容Report,并根据它们携带的类型.最后,List<Graph>根据地图的条目构建一个.
使用Java 8(未经测试),流和collect()假设reports是List<Reports>:
List<Graph> graphs = new ArrayList<>(reports // we want a list - so let's create one. The rest of the code is just to give it some initial contents
.stream() // stream of reports
.collect(HashMap<String, Graph>::new, //collect them - start with a map of date -> grap
(map, report)->{ // here, for each report:
// pick a graph instance for the date, create one if it does not exist yet
Graph graph = map.computeIfAbsent(report.date, date -> new Graph(report.date));
// Next, populate the graph instance based on report type
if ("A".equals(report.type)) { graph.numberA = report.count; }
else if ("B".equals(report.type)) { graph.numberB = report.count; }
else if ("C".equals(report.type)) { graph.numberC = report.count; }
},
Map::putAll) // see collect() javadoc for a description of why this is here
.values()); // last step - get all values from the map (it's a Collection)
Run Code Online (Sandbox Code Playgroud)
编辑:修复编译错误,编辑2:添加代码注释
编辑3:上述代码未在图表中将"0"设置为默认值(对于给定日期/类型组合,报告不存在的情况).我建议在Graph类中处理它(String numberA ="0"等).否则,默认值当然是nulls.