使用 Java8 流从 List<Obj> 中查找总值

Find total of a value from List<Obj> using Java8 streams

以下是我的 json 请求。我的要求是找到 "cols"."value" 字段的总数 if "cols"."name"="tran_amt".

{
  "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”的第一个对象中检索“值”(在本例中为 562356)。它不会对符合条件的所有“值”求和。

任何关于我错的地方的输入?

提前致谢。

如果你想在 0 index[=15] 的第一个 table 的所有 Records 中总结 Colvalue 字段的所有值=]

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();
             

试试这个:

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();