概述
主要用来做数据转换
function函数式接口的方法
抽象方法
R apply(T t);将参数t的数据类型从T类型转换为R类型
默认方法
andThen:该方法是先做前一步操作接着做下一步操作
案例演示
1.有一个字符串,把数字部分提取出来
2.把字符串的数字转换成数字类型
3.将得到的数据进行操作
1 public static void main(String[] args) { 2 String str = "HelloWorld,100"; 3 // 方法一:lambda 4 int fun = fun(str, s -> s.split(",")[1], s -> Integer.parseInt(s),s -> s += 100); 5 // 方法二:lambda表达式+方法引用 6 int fun2 = fun(str, s -> s.split(",")[1], Integer::parseInt, s -> s += 100); 7 System.out.println(fun); 8 System.out.println(fun2); 9 10 // 方法三:匿名内部类的方法 11 Function<String, String> f1 = new Function<>() { 12 @Override 13 public String apply(String s) { 14 return s.split(",")[1]; 15 } 16 }; 17 Function<String, Integer> f2 = new Function<>() { 18 @Override 19 public Integer apply(String s) { 20 return Integer.parseInt(s); 21 } 22 }; 23 Function<Integer, Integer> f3 = new Function<>() { 24 @Override 25 public Integer apply(Integer integer) { 26 return integer += 100; 27 } 28 }; 29 Integer apply = f1.andThen(f2).andThen(f3).apply(str); 30 System.out.println(apply); 31 } 32 33 private static int fun(String s, Function<String, String> one, Function<String, Integer> two, Function<Integer, Integer> three) { 34 Integer apply = one.andThen(two).andThen(three).apply(s); 35 return apply; 36 }