如果我可以将下面代码中的两个 forEach()
循环替换为 Java Stream,有什么建议吗?
注意:对我来说,挑战是如果 firstConjCpnHistMap
中存在任何具有相似键的项目,那么我不想替换它,即我想跳过该迭代...这意味着这个问题有 2 个问题:
- 如何避免两个
forEach()
循环 - 有没有办法在将键/值放入
Map
中时,如果存在相似的键,则不要替换它,这与HashMap<的行为相反
即每当发生 put 操作时进行替换。
public List<TicketingDocumentServiceCouponHistory> build(GetTicketingDocumentRS rs) {
LOGGER.debug("Building FirstConjCpnHistList for TKTRES - 137");
Map<BigInteger, TicketingDocumentServiceCouponHistory> firstConjCpnHistMap = new HashMap<>();
rs.getDetails()
.get(0)
.getTicket()
.getHistory()
.forEach(history -> history.getServiceCouponHistory()
.forEach(couponHistory -> {
if (couponHistory.getCoupon().intValue() % 4 == 1 &&
!couponHistory.getCoupon().equals(BigInteger.ONE) &&
!firstConjCpnHistMap.containsKey(couponHistory.getCoupon())) {
firstConjCpnHistMap.put(couponHistory.getCoupon(), couponHistory);
}
}));
return new ArrayList<>(firstConjCpnHistMap.values());
}
最佳答案
rs.getDetails()
.get(0)
.getTicket()
.getHistory()
.flatMap(history->history.getServiceCouponHistory().stream())
.forEach(couponHistory -> {
if (couponHistory.getCoupon().intValue() % 4 == 1 &&
!couponHistory.getCoupon().equals(BigInteger.ONE)) {
firstConjCpnHistMap.putIfAbsent(couponHistory.getCoupon(), couponHistory);
}
});
关于java - 如何将两个 forEach() 循环替换为 Java Stream?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56969019/