|
| 1 | +# <img src="https://raw.githubusercontent.com/bobocode-projects/resources/master/image/logo_transparent_background.png" height=50/> Functional programming tutorial |
| 2 | + |
| 3 | +This is the tutorial on functional programming basics |
| 4 | +### Pre-conditions :heavy_exclamation_mark: |
| 5 | +You're supposed to be familiar with OOP, have basic knowledge of JDK, and be able to write Java code. |
| 6 | + |
| 7 | +### See also :point_down: |
| 8 | +* [Tutorial on Lambdas](https://github.com/bobocode-projects/java-functional-features-tutorial/tree/master/lambdas) |
| 9 | +* [Tutorial on Stream API](https://github.com/bobocode-projects/java-8-tutorial/tree/master/stream-api) |
| 10 | +* [Tutorial on Optional](https://github.com/bobocode-projects/java-functional-features-tutorial/tree/master/optional) |
| 11 | +## |
| 12 | +The concept of **functional programming** is based on [λ-calculus](https://en.wikipedia.org/wiki/Lambda_calculus). Which |
| 13 | +brings the idea of program that **does not use mutable variables** |
| 14 | + |
| 15 | +Various functional languages like [Clojure](https://clojure.org/) have been using this approach for the long time. **Java** |
| 16 | +was initially created as pure OO language, but since **version 8** it offers an ability to use either **OO and functional |
| 17 | + approaches.** |
| 18 | + |
| 19 | +Consider an program that calculates **the sum of first 20 prime numbers**. |
| 20 | + |
| 21 | +Here's an OO-based implementation: |
| 22 | + |
| 23 | +```java |
| 24 | +public class OOSumOfPrimes { |
| 25 | + public static void main(String[] args) { |
| 26 | + int sumOfPrimes = 0; |
| 27 | + for (int i = 0, primes = 0; primes < 20; i++) { |
| 28 | + if (isPrime(i)) { |
| 29 | + sumOfPrimes += i; |
| 30 | + primes++; |
| 31 | + } |
| 32 | + } |
| 33 | + |
| 34 | + System.out.println("Sum of first 20 primes: " + sumOfPrimes); |
| 35 | + } |
| 36 | + |
| 37 | + private static boolean isPrime(int n) { |
| 38 | + for (int i = 2; i < n; i++) { |
| 39 | + if (n % i == 0) { |
| 40 | + return false; |
| 41 | + } |
| 42 | + } |
| 43 | + return true; |
| 44 | + } |
| 45 | +} |
| 46 | +``` |
| 47 | + |
| 48 | +And this is the functional-based implementation: |
| 49 | +```java |
| 50 | +public class FunctionalSumOfPrimes { |
| 51 | + public static void main(String[] args) { |
| 52 | + IntStream.iterate(0, i -> i + 1) |
| 53 | + .filter(FunctionalSumOfPrimes::isPrime) |
| 54 | + .limit(20) |
| 55 | + .reduce((a, b) -> a + b) |
| 56 | + .ifPresent(sum -> System.out.println("Sum of first 20 primes: " + sum)); |
| 57 | + } |
| 58 | + |
| 59 | + private static boolean isPrime(int n) { |
| 60 | + return IntStream.range(2, n) |
| 61 | + .noneMatch(i -> n % i == 0); |
| 62 | + } |
| 63 | +} |
| 64 | +``` |
| 65 | + |
| 66 | +As you can see there is **no mutable variables** in the second example |
0 commit comments