【发布时间】: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