【问题标题】:Find total of a value from List<Obj> using Java8 streams使用 Java 8 流从 List<Object> 中查找总值
【发布时间】:2021-05-31 04:51:01
【问题描述】:

以下是我的 json 请求。如果 "cols"."name"="tran_amt".

,我的要求是找到 "cols"."value" 字段的总数
{
  "request" : {
    "reqID" : "6839796504132",
    "processID" : 97904250,
    "tables" : [ {
      "tableName" : "TABLE_NAME",
      "records" : [ {
        "recordID" : "record_id1",
        "cols" : [ {
          "name" : "tran_amt",
          "type" : "VARCHAR2",
          "value" : "562356"
        }, {
          "name" : "tran_id",
          "type" : "VARCHAR2",
          "value" : "123456"
        } ]
      }, {
        "recordID" : "record_id2",
        "cols" : [ {
          "name" : "tran_amt",
          "type" : "VARCHAR2",
          "value" : "987098"
        }, {
          "name" : "tran_id",
          "type" : "VARCHAR2",
          "value" : "123456"
        } ]
      } ]
    } ]
  }
}

这是我尝试过的解决方案,

cols = request.getTables().get(0).getRecords().get(0).getCols();
total = cols.stream().filter(o -> "tran_amt".equalsIgnoreCase(o.getName())).mapToInt(o -> Integer.valueOf(o.getValue())).sum();

我的解决方案仅从“cols”的第一个 obj 中检索“值”(在本例中为 562356)。它不会对符合条件的所有“值”求和。

关于我错在哪里的任何意见?

提前致谢。

【问题讨论】:

  • ...getRecords().get(0)... 似乎只获取集合中的第一条记录。您需要遍历所有记录。从概念上讲,流过...getRecords()

标签: java collections java-8 stream java-stream


【解决方案1】:

如果你想总结Col 中所有Recordsvalue 字段的所有值,用于0 索引处的第一个表

total = getTables().get(0)
             .getRecords()
             .stream()
             .map(Col::getCols)
             .flatMap(List::stream)
             .filter(o -> "tran_amt".equalsIgnoreCase(o.getName()))
             .mapToInt(o -> Integer.valueOf(o.getValue())).sum();
             

【讨论】:

    【解决方案2】:

    试试这个:

    total = request.getTables()
                   .stream()
                   .flatMap(t -> t.getRecords().stream())
                   .flatMap(r -> r.getCols().stream())
                   .filter(c -> "tran_amt".equalsIgnoreCase(c.getName()))
                   .mapToInt(c -> Integer.valueOf(c.getValue()))
                   .sum();
    

    【讨论】:

      猜你喜欢
      • 2019-12-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-12-01
      • 1970-01-01
      • 1970-01-01
      • 2016-08-19
      相关资源
      最近更新 更多