我有一个 List<report>
在 Java 中,我想将其更改为 List<graph>
万一
class report {
String date;
String type;
String count;
}
class graph{
String date;
String numberA;
String numberB;
String numberC;
}
例如我有:
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
我知道通过一些 if(条件)和迭代,这是可能的,但是是否有其他解决方案?
任何答案将不胜感激。
最佳答案
你想要一个 Graph
每个日期的实例。因此,存储 Graph
实例到保留一个 Graph
的 map 中每个日期。遍历报告列表并构建 Graph
的内容(numberA, numberB, numberC) 作为 Report
实例进来,并基于它们携带的类型。
最后,构建一个 List<Graph>
基于 map 的条目。
使用 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)
编辑:修复了编译错误, 编辑 2:添加代码注释
编辑 3:上面的代码没有将“0”设置为图表中的默认值(对于给定日期/类型组合不存在报告的情况)。我建议在 Graph 类中处理这个问题( String numberA = "0"等)。否则,默认值为 null
当然。
关于java - 如何将对象列表简化为另一个列表?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50816957/