Java 8 在java8中迭代时如何有效地检查if-else条件?

Java 8 在java8中迭代时如何有效地检查if-else条件?,java-8,Java 8,我正在做一个购物项目。目前我有一张Shoppingcart地图,其中包含Shoppingcart和数量。我必须迭代OrderlineDtolist 并将它们添加到ShoppingcartMap。我已经尝试并实现了它,但我不确定这是最好的。如果还有其他出路,请告诉我 下面是我的代码片段。如果有更好的办法,请告诉我 orderLineDTOList.stream().forEach((orderLineDTO) -> { if (orderLineDTO != null &am

我正在做一个购物项目。目前我有一张
Shoppingcart
地图,其中包含Shoppingcart和数量。我必须迭代
OrderlineDtolist
并将它们添加到
ShoppingcartMap
。我已经尝试并实现了它,但我不确定这是最好的。如果还有其他出路,请告诉我

下面是我的代码片段。如果有更好的办法,请告诉我

orderLineDTOList.stream().forEach((orderLineDTO) -> {
        if (orderLineDTO != null && orderLineDTO.getTempQuantity() != null && orderLineDTO.getTempQuantity() > 0) {
            if (shoppingCartItemMap.containsKey(orderLineDTO.getProduct().getProductCode())) {
                shoppingCartItem = shoppingCartItemMap.get(orderLineDTO.getProduct().getProductCode());
                shoppingCartItem.setQuantity(orderLineDTO.getTempQuantity());
            } else {
                shoppingCartItem = new ShoppingCartItem(orderLineDTO.getProduct(), orderLineDTO.getTempQuantity());
            }
            getSession().getShoppingCartItemMap().put(orderLineDTO.getProduct().getProductCode(), shoppingCartItem);
        }
    });

Java-8没有提供任何新的特定构造来替换
if
语句。但是,您可以在此处使用新方法,如
Stream.filter
Map.computeIfAbsent
,以提高可读性:

orderLineDTOList.stream()
    .filter(orderLineDTO -> orderLineDTO != null && 
            orderLineDTO.getTempQuantity() != null && orderLineDTO.getTempQuantity() > 0)
    .forEach((orderLineDTO) -> 
        shoppingCartItemMap.computeIfAbsent(orderLineDTO.getProduct().getProductCode(),
            code -> new ShoppingCartItem(orderLineDTO.getProduct(), 0)
        ).setQuantity(orderLineDTO.getTempQuantity()));

我假设
getSession().getShoppingCartItemMap()
shoppingCartItemMap
Java-8没有提供任何新的特定构造,它将替换
if
语句。但是,您可以在此处使用新方法,如
Stream.filter
Map.computeIfAbsent
,以提高可读性:

orderLineDTOList.stream()
    .filter(orderLineDTO -> orderLineDTO != null && 
            orderLineDTO.getTempQuantity() != null && orderLineDTO.getTempQuantity() > 0)
    .forEach((orderLineDTO) -> 
        shoppingCartItemMap.computeIfAbsent(orderLineDTO.getProduct().getProductCode(),
            code -> new ShoppingCartItem(orderLineDTO.getProduct(), 0)
        ).setQuantity(orderLineDTO.getTempQuantity()));

我假设
getSession().getShoppingCartItemMap()
shoppingCartItemMap
相同,谢谢你的回答谢谢你的回答