From a37f8801d4db0ce08eaab38fa8c42e481c415153 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Pawe=C5=82=20Dyda?= Date: Sat, 12 Nov 2022 20:25:28 +0100 Subject: [PATCH] Same example expressed functionally. --- .../amu/edu/demo/primes/FunctionalPrimes.java | 30 +++++++++++++++++++ 1 file changed, 30 insertions(+) create mode 100644 demo/03/src/main/java/pl/amu/edu/demo/primes/FunctionalPrimes.java diff --git a/demo/03/src/main/java/pl/amu/edu/demo/primes/FunctionalPrimes.java b/demo/03/src/main/java/pl/amu/edu/demo/primes/FunctionalPrimes.java new file mode 100644 index 0000000..da859d9 --- /dev/null +++ b/demo/03/src/main/java/pl/amu/edu/demo/primes/FunctionalPrimes.java @@ -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); + } + +}