java - 如何将对象列表简化为另一个列表?

标签 java

我有一个 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() ,假设 reportsList<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/

相关文章:

java - spring 框架中 Service 和 DAO 接口(interface)的主要目的是什么?

java - 从字符串数组到 block 图

java - 如何扩展只需要新参数的方法?

java - TensorFlow 标签号与轴上的形状不匹配

Java MVC ActionListener NullPointerException

java - AWS S3 Java SDK - ListVersionsRequest 仅获取最新版本

java.lang.ClassCastException : [Ljava. lang.Object 或 LazyInitializationException 异常

java - DELETE 查询未从数据库表中删除

java - 如何停止使用 "Gradle application plugin"运行的应用程序?

java - 如何从 JavaScriptInterface 启动抽屉导航