内置函数式接口 Function(功能性)

文章介绍了Java中的Function接口,它是一个功能性接口,包含有参有返的方法apply。示例展示了Function接口的传统实现方式和使用lambda表达式的简洁方式。此外,还解释了compose方法用于函数组合,andThen方法用于函数串联,以及identity方法的用途。在示例中,这些方法被应用于字符串处理和集合操作中。
摘要由CSDN通过智能技术生成

Function(功能性)定义

Function(功能性): 有参有返

@FunctionalInterface
public interface Function<T, R> {

    R apply(T t);

    default <V> Function<V, R> compose(Function<? super V, ? extends T> before) {
        Objects.requireNonNull(before);
        return (V v) -> apply(before.apply(v));
    }

    default <V> Function<T, V> andThen(Function<? super R, ? extends V> after) {
        Objects.requireNonNull(after);
        return (T t) -> after.apply(apply(t));
    }

    static <T> Function<T, T> identity() {
        return t -> t;
    }

接口实现方式

# 方式1: 传统方式
Function<String, Integer> function = new Function<String, Integer>() {
    @Override
    public Integer apply(String s) {
        return s.length();
    }
};

# 方式2: lambda表达式
Function<String, Integer> function = (s)-> s.length();

List<Integer> list2 = Stream.of("aaa", "bbbbb", "ccccccv").map(function).toList();

接口使用

# compose
Function<Integer, Integer> after = i -> i * 2; // 扩大两倍
Function<Integer, Integer> before = i -> i * i; // 求平方
//32 先平方再乘2 → 先4×4然后16×2
System.out.println(after.compose(before).apply(4));//32

# andThen
Function<Integer, Integer> before = i -> i * 2; // 扩大两倍
Function<Integer, Integer> after = i -> i * i; // 求平方
//64 先乘2再平方 → 先4×2然后8×8
System.out.println(before.andThen(after).apply(4)); // 64

# identity
Map<String, Integer> map = Stream.of("This", "is", "a", "test").collect(Collectors.toMap(Function.identity(), String::length));
Map<String, Integer> map = list.stream().collect(Collectors.toMap(str -> str, str -> str.length()));
// {a=1, test=4, This=4, is=2}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值