如何将两个forEach()循环替换为Java Stream?

时间:2019-07-10 10:44:26

标签: java

是否有人建议我可以在下面的代码中将两个forEach()循环替换为Java Stream?

注意:对我来说,挑战在于firstConjCpnHistMap中是否存在任何具有相似密钥的项目,那么我不想替换它,即我想跳过该迭代……这意味着这个问题确实有2个问题:

  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 个答案:

答案 0 :(得分:1)

  1. 使用Stream.flatMap()
  2. 使用Map.putIfAbsent()
const filteredArray = objList.filter(o => keyList.includes(o.id));
console.log(filteredArray);