-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path_FunctionsExample.java
More file actions
64 lines (47 loc) · 1.98 KB
/
Copy path_FunctionsExample.java
File metadata and controls
64 lines (47 loc) · 1.98 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
package functionalprogramming;
import java.util.function.BiFunction;
import java.util.function.Function;
public class _FunctionsExample {
/*
Here we show an example of how to use functional programming with a
declarative approach for creating functions.
Functions always take in arguments AND return arguments.
Thats with regular Functions and BiFunctions.
We use the ".apply()" method with Functions.
*/
static Function<String, String> returnTheString = name -> name;
public static void main(String[] args) {
// this is how we usually call functions in java.
System.out.println(decrement(50)); // returns 49
// now we can call the String Function method like this
String names = returnTheString.apply("Stefan Bayne");
System.out.println(names);
// this is the functional approach using the function interface
Function<Integer, Integer> incrementByOne = x -> x + 1;
// here we will create a multiply method to show how to chain functions
Function<Integer, Integer> multiplyByOne = x -> x * 50;
Function<Integer, Integer> andOneMultiplyByOne =
incrementByOne.andThen(multiplyByOne);
System.out.println(andOneMultiplyByOne.apply(10)); // returns 550
System.out.println(andOneMultiplyByOne.apply(46)); // returns 2350
/**
* BiFunctions are the same except they take two parameters.
*
* Takes two integer arguments and returns one integer.
*
* Similar to the reduce function.
*/
BiFunction<Integer, Integer, Integer> incrementThanMultiply =
(numToIncrement, numToMultiply) -> (numToIncrement + 1) * numToMultiply;
System.out.println(incrementThanMultiply.apply(10, 20)); // returns 220
}
// typical approach aka Imperative approach
static int decrement(int a) {
return a - 1;
}
/*
Output:
49
Stefan Bayne
*/
}