|
| 1 | +package cn.delei.java.feature; |
| 2 | + |
| 3 | +import cn.delei.util.PrintUtil; |
| 4 | + |
| 5 | +import java.util.Arrays; |
| 6 | +import java.util.List; |
| 7 | +import java.util.function.Consumer; |
| 8 | +import java.util.function.Function; |
| 9 | +import java.util.function.Predicate; |
| 10 | +import java.util.function.Supplier; |
| 11 | + |
| 12 | +/** |
| 13 | + * 函数式编程Demo |
| 14 | + * |
| 15 | + * @author deleiguo |
| 16 | + * @since 1.8 |
| 17 | + */ |
| 18 | +public class FunctionInterfaceDemo { |
| 19 | + public static void main(String[] args) { |
| 20 | + jdkFunction(); |
| 21 | + } |
| 22 | + |
| 23 | + static void jdkFunction() { |
| 24 | + PrintUtil.printDivider("Consumer"); |
| 25 | + Consumer<String> c1 = System.out::println; |
| 26 | + Consumer<String> c2 = s -> System.out.println(s + "-Consumer"); |
| 27 | + c1.accept("111"); |
| 28 | + c2.accept("222"); |
| 29 | + c1.andThen(c1).andThen(c2).accept("3333"); |
| 30 | + |
| 31 | + PrintUtil.printDivider("Function"); |
| 32 | + Function<Integer, Integer> f = s -> s * 2; |
| 33 | + Function<Integer, Integer> g = s -> s + 2; |
| 34 | + /* |
| 35 | + * 下面表示在执行F时,先执行G,并且执行F时使用G的输出当作输入。 |
| 36 | + * 相当于以下代码: |
| 37 | + * Integer a = g.apply(1); |
| 38 | + * System.out.println(f.apply(a)); |
| 39 | + */ |
| 40 | + System.out.println(f.compose(g).apply(1)); |
| 41 | + /* |
| 42 | + * 表示执行F的Apply后使用其返回的值当作输入再执行G的Apply; |
| 43 | + * 相当于以下代码 |
| 44 | + * Integer a = f.apply(1); |
| 45 | + * System.out.println(g.apply(a)); |
| 46 | + */ |
| 47 | + System.out.println(f.andThen(g).apply(1)); |
| 48 | + // identity方法会返回一个不进行任何处理的Function,即输出与输入值相等; |
| 49 | + System.out.println(Function.identity().apply("a")); |
| 50 | + |
| 51 | + PrintUtil.printDivider("Predicate"); |
| 52 | + List<String> strList = Arrays.asList("Java", "JavaScript", "C", "C++", "C#", "PHP", "Go"); |
| 53 | + Predicate<String> conditon = (str) -> str.length() > 6; |
| 54 | + filter(strList, conditon); |
| 55 | + filter(strList, s -> s.startsWith("C")); |
| 56 | + Predicate<String> p1 = s -> s.equals("Java"); |
| 57 | + Predicate<String> p2 = s -> s.startsWith("JavaScript"); |
| 58 | + // negate: 用于对原来的Predicate做取反处理; |
| 59 | + System.out.println(p1.negate().test("JavaScript")); |
| 60 | + // and: 针对同一输入值,多个Predicate均返回True时返回True,否则返回False; |
| 61 | + System.out.println(p1.and(p2).test("JavaScript")); |
| 62 | + // or: 针对同一输入值,多个Predicate只要有一个返回True则返回True,否则返回False |
| 63 | + System.out.println(p1.or(p2).test("Java")); |
| 64 | + |
| 65 | + PrintUtil.printDivider("Supplier"); |
| 66 | + Supplier<String> supplier = () -> "sss"; |
| 67 | + System.out.println(supplier.get()); |
| 68 | + } |
| 69 | + |
| 70 | + static void filter(List<String> list, Predicate<String> predicate) { |
| 71 | + list.stream().filter((s) -> (predicate.test(s))).forEach((s) -> { |
| 72 | + System.out.println(s + " #"); |
| 73 | + }); |
| 74 | + System.out.println(""); |
| 75 | + } |
| 76 | +} |
0 commit comments