JDK8 新特性

Lambda 表达式

语法

(参数) -> {方法体}

A res1 = () -> System.out.println("test方法");
A res2 = (a, b) -> System.out.println(a);
A res3 = (a, b) -> a + b;
A res4 = (a, b) -> { return a + b; };
interface A {
    void test();
    void add(int a, int b);
    int add(int a, int b);
}

函数式接口

定义:只包含一个抽象方法的接口 称为函数式接口

Lambda表达式和函数式接口的关系:

Lambda表达式就是一个函数式接口的实例

内置函数式接口

Predicate<T>断定型接口

断定型接口,接受一个输入参数,返回一个布尔值结果。

class Main {
    public static void main(String[] args) {
        List<Integer> list = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9);
        System.out.println(list);
        //输出所有偶数:
        eval(list, integer -> integer % 2 == 0);
        //输出大于 3 的所有数字
        eval(list, i -> i > 3);
    }

    public static void eval(List<Integer> list, Predicate<Integer> predicate) {
        for (Integer n : list) {
            if (predicate.test(n)) {
                System.err.print(n + "\t");
            }
        }
    }
}
Supplier 供给型接口

本质就是一个容器,可以用来存储数据(或者是产生数据的规则),然后可以供其他方法使用的这么一个接口。

class Main {
    public static void main(String[] args) {

        Supplier<Integer> supplier = new Supplier<Integer>() {
            @Override
            public Integer get() {
                return new Random().nextInt(100);
            }
        };
        System.out.println(supplier.get());
        System.out.println(supplier.get());
        //这里Supplier.get()等价于new Random().nextInt(100)
    }
}
Consumer<T>消费型接口

与Supplier接口相反,它不是生产一个数据,而是消费一个数据其数据类型由泛型决定

class Main {
    public static void main(String[] args) {
      eval("codingfuture", new Consumer<>() {
          @Override
          public void accept(String s) {
              System.out.println(s.toUpperCase());
          }
      });
    }

    public static void eval(String name, Consumer<String> consumer) {
        consumer.accept(name);
    }
}
Function<T,R>函数型接口

对类型为T的对象应用操作返回类型为R的对象

class Main {
    public static void main(String[] args) {
        //字符串 转换 Integer
        Integer trimStr = strHandler("666", s -> Integer.valueOf(s));
        System.out.println(trimStr);
    }

    //对类型为T的对象应用操作返回类型为R的对象 Function<T,R>
    public static Integer strHandler(String str, Function<String, Integer> fun) {
        return fun.apply(str);
    }
}
自定义函数接口
@FunctionalInterface
public interface Operation {
    int add(Integer num1, Integer num2);
}

class Main {
    public static void main(String[] args) {
        eval(12, 13, (num1, num2) -> num1 + num2);
    }

    public static void eval(int a, int b, Operation operation) {
        int res = operation.add(a, b);
        System.out.println(res);
    }

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值