这里写目录标题
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}