PaulJRobbins
PaulJRobbins

Reputation: 3

Arbitrary number of operations in lambda function in Java

I have a simple lambda function to calculate the total of integer multiples in a certain range. Right now it is totaling multiples of 3 and 5.

System.out.println(IntStream.rangeClosed(1, 999)
            .boxed().collect(Collectors.toList())
            .stream().filter(n -> n%3 == 0 || n%5 == 0).collect(Collectors.toList()));

I would like to take an arbitrary list of numbers and write a lambda function that checks a range for multiples of all those numbers. i.e. if I pass in 3 & 5 I want multiples of those, if i pass 6, 9, 11 i want multiples of those three. I imagine it looks something like this:

System.out.println(IntStream.rangeClosed(1, 999)
            .boxed().collect(Collectors.toList())
            .stream().filter(n -> for(int mult : multiples)if(n%mult==0)).collect(Collectors.toList()));

Is this possible or do lambdas require a fixed number of operations?

Upvotes: 0

Views: 92

Answers (1)

garnulf
garnulf

Reputation: 366

You can stream your multiples as well and use anyMatch. Also note that you don't need to collect in between, you usually only want to collect when all your work is done on the Stream. The boxing can be done right before collecting, until then you can work with the IntStream.

int[] multiples = { 3, 5, 7 };
System.out.println(IntStream.rangeClosed(1, 999)
    .filter(n -> IntStream.of(multiples).anyMatch(k -> n % k == 0))
    .boxed()
    .collect(Collectors.toList()));

Upvotes: 1

Related Questions