我正在新学习lambda表达式。我正在尝试计算值。
这里是示例:
int sendersCount = 0.0;
int reciversCount = 0.0;
for(Record record : records){
if("1".equals(record.getSendersId()) {
sendersCount += record.getSendersCount();
} else {
reciversCount += record.getReciversCount();
}
}
如何使用流和地图来实现?
以一种方式,您可以对列表进行分区,然后将适当的属性sum
分区为-->
Map<Boolean, List<Record>> partitioned = records.stream()
.collect(Collectors.partitioningBy(rec -> rec.getSendersId().equals("1")));
int sendersCount = partitioned.get(Boolean.TRUE).stream()
.mapToInt(Record::getSendersCount).sum();
int reciversCount = partitioned.get(Boolean.FALSE).stream()
.mapToInt(Record::getReciversCount).sum();