Same example expressed functionally.

This commit is contained in:
Paweł Dyda 2022-11-12 20:25:28 +01:00
parent 04a7696d53
commit a37f8801d4
1 changed files with 30 additions and 0 deletions

View File

@ -0,0 +1,30 @@
package pl.amu.edu.demo.primes;
import lombok.NoArgsConstructor;
import java.util.function.IntPredicate;
import java.util.stream.IntStream;
@NoArgsConstructor
public class FunctionalPrimes {
public static void main(String[] args) {
new FunctionalPrimes().printPrimes();
}
public void printPrimes() {
IntStream.range(0, 121)
.filter(this::isPrime)
.forEach(i -> System.out.printf("%d is prime\n", i));
}
private boolean isPrime(int number) {
if (number <= 0) {
return false;
}
IntPredicate isDivisible = (int divisor) -> number % divisor == 0;
return IntStream.rangeClosed(2, (int) Math.sqrt(number))
.noneMatch(isDivisible);
}
}