Same example expressed functionally.
This commit is contained in:
parent
04a7696d53
commit
a37f8801d4
@ -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);
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
Loading…
Reference in New Issue
Block a user