【发布时间】:2015-11-05 11:13:31
【问题描述】:
我对 java 8 流完全陌生,我正在尝试获得以下描述的行为:
class myVO {
Long id;
BigDecimal value;
Date date;
getter/setter
}
myVO method(Map<Long, myVO> inputMap) {
return inputMap.stream()
.filter(x -> x.getValue().compareTo(BigDecimal.ZERO) > 0)
.sorted(); //FIXME
}
我只想获得一个myVO obj,它是同一日期(最低)记录的BigDecimal 值的总和。
例如
xL, 10, 2015/07/07
xL, 15, 2015/07/08
xL, 20, 2015/07/07
xL, 25, 2015/07/09
结果
xL, 30, 2015/07/07
注意id (xL) 不是重要字段。
更新——采用的解决方案(虽然不是单次通过)
if(null != map && !map.isEmpty()) {
Date closestDate = map.values().stream()
.filter(t -> t.getDate() != null)
.map(MyVO::getDate)
.min(Comparator.naturalOrder()).orElse(null);
myVO.setDate(closestDate);
BigDecimal totalValue = map.values().stream()
.filter(x -> x.getValue() != null && x.getValue().signum() != 0)
.filter(t -> t.getDate().equals(closestDate))
.map(MyVO::getValue)
.reduce(BigDecimal::add).orElse(null);
myVO.setValue(totalValue != null ? totalValue.setScale(2, BigDecimal.ROUND_HALF_DOWN) : totalValue);
}
【问题讨论】:
标签: java dictionary java-8 java-stream reduce