常用函数式接口之Function接口

概述

主要用来做数据转换

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     }

 

转载于:https://www.cnblogs.com/leonHQ/p/9528388.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值