四大类函数式接口

供给型接口

Supplier<T>     返回T类型对象
    T get();
Supplier<Apple> supplier = () -> new Apple();
// Supplier<Apple> supplier = Apple::new;
supplier.get();

消费型接口

Consumer<T>     接收一个 T 类型
    void accept(T t);
List<String> languages = Arrays.asList("java","scala","python");
Consumer<String> consumer = System.out::println;
languages.stream().forEach(consumer);

函数型接口

Function<T, R>  由T类型对象转成R类型对象
    R apply(T t);
List<String> languages = Arrays.asList("java","scala","python");
Function<String, Integer> ti = String::length;
languages.stream()
    .map(ti)
    .forEach(System.out::println);

断言型接口

Predicate<T>    条件判断
    boolean test(T t);
List<String> languages = Arrays.asList("java","scala","python");
Predicate<String> p = (str) -> str.length() > 4;
languages.stream()
    .filter(p)
    .forEach(System.out::println);

一个简单的使用多个函数式接口的例子:

List<String> languages = Arrays.asList("java","scala","python");
Function<String, Integer> ti = String::length;
BiConsumer<Integer, String> bi = (a, b) -> System.out.println(b + a);
IntPredicate ip = x -> x > 4;
IntPredicate ip1 = x -> x < 100;
IntUnaryOperator io = x -> x * x;
languages.stream()
    .map(ti)
    .map(io::applyAsInt)
    .filter(x->ip.and(ip1).test(x))
    .forEach(x -> bi.accept(x, "prefix_"));

部分函数式接口中有 default 方法, 可以进行组合使用!

转载于:https://www.cnblogs.com/wansw/p/10225928.html

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值