10000 add Function demo examples · fishercoder1534/RandomJava@a768af2 · GitHub
[go: up one dir, main page]

Skip to content

Commit a768af2

Browse files
add Function demo examples
1 parent 1145836 commit a768af2

File tree

1 file changed

+61
-0
lines changed

1 file changed

+61
-0
lines changed
Lines changed: 61 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,61 @@
1+
package java8tutorials.functionalInterfaces;
2+
3+
import java.util.concurrent.ExecutionException;
4+
import java.util.function.Function;
5+
6+
public class FunctionDemo {
7+
8+
public static void main(String... args) throws ExecutionException, InterruptedException {
9+
System.out.println("Program started.");
10+
FunctionDemo main = new FunctionDemo();
11+
String originalInput = "originalInput";
12+
String result = main.doWorkInMultipleStepsInSequence(originalInput);
13+
System.out.println("Program ended, result: " + result);
14+
}
15+
16+
String doWorkInMultipleStepsInSequence(String messageOne) throws InterruptedException {
17+
return doWorkStepTwoAsync(messageOne, doWorkStepTwoFunction);
18+
}
19+
20+
String doWorkStepTwoAsync(String message, Function<String, String> doWorkStepTwoFunction) throws InterruptedException {
21+
Thread.sleep(1000);
22+
StringBuilder sb = new StringBuilder(message);
23+
System.out.println("Spent 1 second doing work in Step Two Async function.");
24+
sb.append(",aboutToCallDoWorkStepTwoFunction");
25+
String intermediateResult = doWorkStepTwoFunction.apply(sb.toString());
26+
return doWorkStepThreeAsync(intermediateResult, doWorkStepThreeFunction);
27+
}
28+
29+
String doWorkStepThreeAsync(String message, Function<String, String> doWorkStepThreeFunction) throws InterruptedException {
30+
Thread.sleep(1000);
31+
StringBuilder sb = new StringBuilder(message);
32+
System.out.println("Spent 1 second doing work in Step Three Async function.");
33+
sb.append(",aboutToCallDoWorkStepThreeFunction");
34+
return doWorkStepThreeFunction.apply(sb.toString());
35+
}
36+
37+
Function<String, String> doWorkStepTwoFunction = s -> {
38+
StringBuilder sb = new StringBuilder(s);
39+
try {
40+
Thread.sleep(1000);
41+
System.out.println("Spent 1 second doing work in Step Two.");
42+
sb.append(",stepTwoDone");
43+
} catch (InterruptedException e) {
44+
throw new RuntimeException(e);
45+
}
46+
return sb.toString();
47+
};
48+
49+
Function<String, String> doWorkStepThreeFunction = s -> {
50+
StringBuilder sb = new StringBuilder(s);
51+
try {
52+
Thread.sleep(1000);
53+
System.out.println("Spent 1 second doing work in Step Three.");
54+
sb.append(",stepThreeDone");
55+
} catch (InterruptedException e) {
56+
throw new RuntimeException(e);
57+
}
58+
return sb.toString();
59+
};
60+
61+
}

0 commit comments

Comments
 (0)
0