Home > Mobile >  Use stream filter only if function parameter is not null
Use stream filter only if function parameter is not null

Time:12-09

Say I have :

public class Car{

private String model;
private Integer price;
   ...
}

public class CarsList {
    private List<Car> cars;

    public List<Car> filterFunction(Integer maxPrice, Integer minPrice) {
        return cars
                .stream()
                .filter(c -> c.getPrice() > minPrice)
                .filter(c -> c.getPrice() < maxPrice)
                .collect(Collectors.toList());
    }
}

However, I have a possibility that the parameters maxPrice OR minPrice or both are null.

Is there a way to use maxPrice and minPrice filters only if function arguments are not null?

I know I could check if parameters aren't null before filtering, but then I would have to have different configuration of filtering for every combination (what would happen if I had 5 parameters).

I'm thinking of something like : stream.filter(minPrice != null || c -> c.getPrice() > minPrice), but I can see why that does not work.

CodePudding user response:

when the minPrice is null, you can return true to skip this filter.

.filter(c ->minPrice==null||c.getPrice() > minPrice)

CodePudding user response:

I assume arguments in the function are going to be all integers, I'd change that to

public List<Car> filterFunction(Integer... args)

Then I'd check if any of them are null:

if (Arrays.stream(args).anyMatch(Objects::isNull))
    return;

After that, I know that all parameters in the function are not null.


If you want the parameters in order, I'd do something similar to above:

public List<Car> filterFunction(Integer maxPrice, Integer minPrice)

Then:

if (Stream.of(minPrice, maxPrice).anyMatch(Objects::isNull))
    return;

Based on last comment:

cars.stream()
    .filter(c -> {
            if (maxPrice == null)
                return c -> c.getPrice() > minPrice;
            if (minPrice == null)
                c -> c.getPrice() < maxPrice;

            return c -> c.getPrice() > minPrice && c -> c.getPrice() < maxPrice;
        })
    .collect(Collectors.toList());

CodePudding user response:

You could only use filter conditionally, depending on the parameters, instead:

            Stream<Car> stream = cars
                    .stream();
            if (Objects.nonNull(maxPrice))
                stream = stream.filter(c -> c.getPrice() < maxPrice);
            if (Objects.nonNull(minPrice))
                stream = stream.filter(c -> c.getPrice() > minPrice);
            return stream
                    .collect(Collectors.toList());
  • Related