[英]Find total of a value from List<Obj> using Java8 streams
以下是我的 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)。 它不会对符合条件的所有“值”求和。
关于我错在哪里的任何意见?
提前致谢。
如果要从第一个表的所有Records
中汇总Col
中value
字段的所有值在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();
尝试这个:
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();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.