Skip to content

Commit bd42aa7

Browse files
committed
class 21 composition
1 parent 507a4e4 commit bd42aa7

1 file changed

Lines changed: 35 additions & 0 deletions

File tree

Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
1+
package com.platzi.functional_student_practice._11_composition;
2+
3+
import java.util.function.IntUnaryOperator;
4+
5+
public class C21MathOperations2 {
6+
public static void main(String[] args) {
7+
System.out.println("////////////////////////////////////////////////////////////////////////////////////");
8+
System.out.println("\nCLASS 21\n");
9+
10+
// 1. We declare 3 functions as variables
11+
IntUnaryOperator multiplyBy3 = x -> { // idem: Function<Integer, Integer>
12+
System.out.println("Multiplicando x: " + x + " por 3");
13+
return x * 3;
14+
};
15+
16+
IntUnaryOperator add1 = x -> {
17+
System.out.println("Le agregare 1 a: " + x);
18+
return x + 1;
19+
};
20+
21+
IntUnaryOperator square = x -> {
22+
System.out.println("Estoy elevando " + x + " al cuadrado");
23+
return x * x;
24+
};
25+
26+
// 2. We compose a new function that execute multiplyBy3() AFTER we add1()
27+
IntUnaryOperator add1MultiplyBy3 = multiplyBy3.compose(add1); // idem: y -> add1.apply(y) - idem: add1::applyAsInt
28+
29+
// 3. We compose a new function that execute add1MultiplyBy3() BEFORE we square()
30+
IntUnaryOperator andSquare = add1MultiplyBy3.andThen(square); // idem: y -> square.apply(y)
31+
32+
System.out.println(add1MultiplyBy3.applyAsInt(5));
33+
System.out.println(andSquare.applyAsInt(3));
34+
}
35+
}

0 commit comments

Comments
 (0)