Search code examples
javadebuggingintellij-idealambdajava-stream

Java stream().filter() cannot find local variable with lamba expression


I want to get the amount of a specific product that is in all warehouses. Warehouses contain a list of products. .filter doenst find the local variable "p" (https://i.sstatic.net/ml1zC.png)

I use .map to get a Stream of Lists of products .flatmap to get a Stream of products and .filter to compare each product"p" to the parameter of the function

public long getQuantityOfProduct(Product product) {
        return warehouses.stream()
            .map(Warehouse::getProducts)
            .flatMap(Collection::stream)
            .filter(p -> p.equals(product))
            .count();
    }

Solution

  • You need to set a breakpoint inside the lambda expression, otherwise the variable will be undefined. Check the Breakpoints guide, it is explained how to set a breakpoint only when the lambda is called.

    If the line contains a lambda expression, you can select whether you want to set a regular line breakpoint, or the program should only be suspended when the lambda is called.

    It's done like this:

    set breakpoint inside lambda