Stream API – need to iterate over the List and compare with Map. Write result in different Map

public class ProductInStockRequest {

private String productId;

private Integer requestedQuantity;

}

I have a List

    requestList.add(new ProductInStockRequest("100", 5));
    requestList.add(new ProductInStockRequest("200", 11));
    requestList.add(new ProductInStockRequest("300", 33));
    requestList.add(new ProductInStockRequest("400", 55));

I have a Map<String, Integer> productInDbMap = new HashMap<>();

    productInDbMap.put("100", 10);
    productInDbMap.put("200", 10);
    productInDbMap.put("300", 44);
    productInDbMap.put("400", 77);

I created new Map<String, String> responseMap = new HashMap<>();

I need to go over each element in List and check if for related productId I have enough quantity or not and write result in responseMap

Trying to do something like this:

    requestList.stream().map(requestedItem -> {
        int quantity = productInDbMap.get(requestedItem.getProductId());

        if (quantity >= requestedItem.getRequestedQuantity()) {
            responseMap.put(requestedItem.getProductId(), "order-able");

        } else {
            int availableQuantity = quantity - requestedItem.getRequestedQuantity();
            String s = String.valueOf(availableQuantity);
            responseMap.put(requestedItem.getProductId(), s);
        }
        return responseMap;
    });

No luck, please advise

>Solution :

you can start with something like this:

        Map<String, String> responseMap = requestList.stream().map(requestedItem -> {
            int quantity = productInDbMap.get(requestedItem.getProductId());

            if (quantity >= requestedItem.getRequestedQuantity()) {
                return new AbstractMap.SimpleEntry<>(requestedItem.getProductId(), "order-able");
            } else {
                int availableQuantity = quantity - requestedItem.getRequestedQuantity();
                String s = String.valueOf(availableQuantity);
                return new AbstractMap.SimpleEntry<>(requestedItem.getProductId(), s);
            }
        }).collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue));

In general, never modify anything from inside the stream or lambdas in general. The compiler will allow it in this case (and will complain in case of modifying a variable), but it’s always a bad practice and unsafe.

Leave a Reply