使用Java转换为Lambda表达式?

问题描述 投票:1回答:1

我正在新学习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();
   }
}

如何使用流和地图来实现?

java java-8 java-stream functional-interface
1个回答
0
投票

以一种方式,您可以对列表进行分区,然后将适当的属性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();
    
© www.soinside.com 2019 - 2024. All rights reserved.