Search code examples
lambdafilterjava-8predicate

IntPredicate Lambda Java8


The functionality of the following method is to try to traverse a list from 3 to 999 by adding the multiples of two numbers, where multiplosDe.get(0) could be 4 and multiplosDe.get(1) could be 7.

This function works if I only send a list with two Integer objects. What I want is to be able to send a list of n objects and do not have to have the need to add || multiplosDe.get(2) to predicate.

public long sumaDeMultiplos(List<Integer> multiplosDe) {
    int suma = 0;
    IntPredicate predicate  = s -> (s%multiplosDe.get(0)==0 || s%multiplosDe.get(1)==0);

        suma = IntStream.range(3, 1000).filter(predicate).sum();

    return suma;
}

Solution

  • IntPredicate predicate  = s -> multiplosDe.stream().anyMatch(i -> s % i == 0);