Skip to content
This repository was archived by the owner on Feb 10, 2021. It is now read-only.

Commit a57715d

Browse files
committed
Add function composition example
1 parent 2abd818 commit a57715d

File tree

1 file changed

+44
-0
lines changed

1 file changed

+44
-0
lines changed
Lines changed: 44 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,44 @@
1+
package com.bobocode;
2+
3+
import java.util.Objects;
4+
import java.util.function.Function;
5+
import java.util.function.IntUnaryOperator;
6+
import java.util.function.Predicate;
7+
8+
/**
9+
* One of functional programming techniques if a function composition. Having two different functions f(x) and g(x) in
10+
* math you would write f(g(x)) to compose those function. The same you can do in Java using method
11+
* {@link IntUnaryOperator#compose} or {@link IntUnaryOperator#andThen(IntUnaryOperator)}
12+
* <p>
13+
* In fact most predefined functional interfaces have similar capabilities.
14+
* E.g. {@link java.util.function.Function#compose(Function)} or {@link Predicate#and(Predicate)}
15+
*/
16+
public class FunctionComposition {
17+
public static void main(String[] args) {
18+
printSquareOfDoubleUsingFunctionComposition();
19+
printStringIsBlankUsingPredicateComposition();
20+
}
21+
22+
private static void printSquareOfDoubleUsingFunctionComposition() {
23+
IntUnaryOperator squareFunction = a -> a * a; // s(x) = x * x
24+
IntUnaryOperator doublerFunction = a -> 2 * a; // d(x) = 2 * x
25+
26+
IntUnaryOperator squareOfDoubleFunction = squareFunction.compose(doublerFunction); // s(d(x))
27+
28+
System.out.println("square(double(3)) = " + squareOfDoubleFunction.applyAsInt(3));
29+
}
30+
31+
private static void printStringIsBlankUsingPredicateComposition() {
32+
Predicate<String> isEmptyPredicate = String::isEmpty;
33+
Predicate<String> isNotNullPredicate = Objects::nonNull;
34+
35+
Predicate<String> isNotBlank = isNotNullPredicate.and(isEmptyPredicate.negate());
36+
37+
String str = "Hi";
38+
System.out.println("String \"" + str + "\" is not blank? " + isNotBlank.test(str));
39+
40+
41+
}
42+
43+
44+
}

0 commit comments

Comments
 (0)