簡體   English   中英

如何將兩個forEach()循環替換為Java Stream?

[英]How to replace two forEach() loops into Java Stream?

如果可以在下面的代碼中將兩個forEach()循環替換為Java Stream,有什么建議嗎?

注意:對我來說,挑戰在於firstConjCpnHistMapfirstConjCpnHistMap存在任何具有相似鍵的firstConjCpnHistMap ,那么我不想替換它,即我想跳過該迭代……這意味着該問題確實有兩個問題:

  1. 如何避免兩個forEach()循環
  2. 將鍵/值放入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());
}
  1. 使用Stream.flatMap()
  2. 使用Map.putIfAbsent()
 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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM