soorapadman
soorapadman

Reputation: 4509

How to check effectively if else condition while iteration in java8?

I am working on a shopping project. Currently I have a map of Shoppingcart which contains shoppingcart and quantity. I have to iterate the OrderlineDtolist and add them to the ShoppingcartMap. I have tried and achieved it but I am not sure this as the best. If there are any other ways out please let me know.

Below is a snippet of my code. Please let me know if there is any better way around.

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);
        }
    });

Upvotes: 0

Views: 633

Answers (1)

Tagir Valeev
Tagir Valeev

Reputation: 100279

Java-8 does not provide any new specific construct which would replace if statements. However here you may utilize new methods like Stream.filter and Map.computeIfAbsent to increase the readability:

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()));

I assume that getSession().getShoppingCartItemMap() is the same as shoppingCartItemMap.

Upvotes: 2

Related Questions