[英]How to replace two forEach() loops into Java Stream?
如果可以在下面的代碼中將兩個forEach()
循環替換為Java Stream,有什么建議嗎?
注意:對我來說,挑戰在於firstConjCpnHistMap
中firstConjCpnHistMap
存在任何具有相似鍵的firstConjCpnHistMap
,那么我不想替換它,即我想跳過該迭代……這意味着該問題確實有兩個問題:
forEach()
循環 Map
,有什么辦法,如果存在相似的鍵,則不要替換它,這與HashMap
行為相反,即在放置操作發生時進行替換。 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);
}
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.