JM学java8笔记2-常见的函数式接口

2、常见的函数式接口

java.util.function包下的为jdk1.8新增的包,里面引入了几个新的函数式接口

接下里就学习几个接口

2.1 Consumer

/**
 * Represents an operation that accepts a single input argument and returns no
 * result. Unlike most other functional interfaces, {@code Consumer} is expected
 * to operate via side-effects.
 *
 * <p>This is a <a href="package-summary.html">functional interface</a>
 * whose functional method is {@link #accept(Object)}.
 *
 * @param <T> the type of the input to the operation
 *
 * @since 1.8
 */
@FunctionalInterface
public interface Consumer<T> {

    /**
     * Performs this operation on the given argument.
     *
     * @param t the input argument
     */
    void accept(T t);

    /**
     * Returns a composed {@code Consumer} that performs, in sequence, this
     * operation followed by the {@code after} operation. If performing either
     * operation throws an exception, it is relayed to the caller of the
     * composed operation.  If performing this operation throws an exception,
     * the {@code after} operation will not be performed.
     *
     * @param after the operation to perform after this operation
     * @return a composed {@code Consumer} that performs in sequence this
     * operation followed by the {@code after} operation
     * @throws NullPointerException if {@code after} is null
     */
    default Consumer<T> andThen(Consumer<? super T> after) {
        Objects.requireNonNull(after);
        return (T t) -> { accept(t); after.accept(t); };
    }
}

这个函数式接口的抽象方法式接受一个入参不返回任何东西,那么些一个例子来作为实践。

public class CosumerPrc {

    public static void main(String[] args) {
		// 字符串拼接
        String str = "hello";
        CosumerPrc cosumerPrc = new CosumerPrc();
		
        cosumerPrc.addStr(str,value -> {
            System.out.println(value + " JM");
        });

    }

    /**
     * @param str  参数
     * @param consumer 用户具体行为
     */
    public void addStr(String str, Consumer<String> consumer){
        consumer.accept(str);
    }
}

// 输出结果: hello JM

将上面的改写如下:

public class CosumerPrc<T> {


    public static void main(String[] args) {


        String str = "hello";
        CosumerPrc<String> cosumerPrc = new CosumerPrc<String>();

        // 将传入的字符串改写为大写
        cosumerPrc.compute(str,value -> {
            System.out.println(str.toUpperCase());
        });
        System.out.println(str + "------------");

        // 将传入的字符串进行替换操作
        cosumerPrc.compute(str,value -> {
            value = value.replace("e","i ");
            System.out.println(value);
        });
        System.out.println(str + "------------");

        //******************************************************//
        int defaultNum = 0 ;
        CosumerPrc<Integer> cPrcInt = new CosumerPrc<Integer>();
        cPrcInt.compute(defaultNum,num -> {
            System.out.println(++num);
        });

        System.out.println(defaultNum + "------------");

    }


    /**
     *  更抽象一点
     *  我们将行为抽象出来一个参数,
     *  执行逻辑由调用者给出
     */

    public void compute(T t,Consumer<T> consumer){
        consumer.accept(t);
    }
}

这里体会下上一章的步骤,

行为参数化 - 把调用的具体行为抽象为consumer接口(使用函数式接口来传递行为) - 执行(获取)一个行为 - 传递 Lambda

关于 andThen方法后续在学习streamAPI的时候在进行学习。

2.2 Function

/**
 * Represents a function that accepts one argument and produces a result.
 *
 * <p>This is a <a href="package-summary.html">functional interface</a>
 * whose functional method is {@link #apply(Object)}.
 *
 * @param <T> the type of the input to the function
 * @param <R> the type of the result of the function
 *
 * @since 1.8
 */
@FunctionalInterface
public interface Function<T, R> {

    /**
     * Applies this function to the given argument.
     *
     * @param t the function argument
     * @return the function result
     */
    R apply(T t);

    /**
     * Returns a composed function that first applies the {@code before}
     * function to its input, and then applies this function to the result.
     * If evaluation of either function throws an exception, it is relayed to
     * the caller of the composed function.
     *
     * @param <V> the type of input to the {@code before} function, and to the
     *           composed function
     * @param before the function to apply before this function is applied
     * @return a composed function that first applies the {@code before}
     * function and then applies this function
     * @throws NullPointerException if before is null
     * 先执行before得apply,然后将执行后的结果做为当前的apply方法传递
     将俩个function接口组合到一起返回值为function
     * @see #andThen(Function)
     */
    default <V> Function<V, R> compose(Function<? super V, ? extends T> before) {
        Objects.requireNonNull(before);
        return (V v) -> apply(before.apply(v));
    }

    /**
     * Returns a composed function that first applies this function to
     * its input, and then applies the {@code after} function to the result.
     * If evaluation of either function throws an exception, it is relayed to
     * the caller of the composed function.
     *
     * @param <V> the type of output of the {@code after} function, and of the
     *           composed function
     * @param after the function to apply after this function is applied
     * @return a composed function that first applies this function and then
     * applies the {@code after} function
     * @throws NullPointerException if after is null
     *
     * @see #compose(Function)
     */
    default <V> Function<T, V> andThen(Function<? super R, ? extends V> after) {
        Objects.requireNonNull(after);
        return (T t) -> after.apply(apply(t));
    }

    /**
     * Returns a function that always returns its input argument.
     *
     * @param <T> the type of the input and output objects to the function
     * @return a function that always returns its input argument
     */
    static <T> Function<T, T> identity() {
        return t -> t;
    }
}

Function是接受一个参数返回一个参数的函数式接口 Function<T, R> 接受T返回R

public class FunctionPrc<T,R> {


    public static void main(String[] args) {


        String hi = "JM, I am jimmy";

        FunctionPrc<String,Integer> functionPrc = new FunctionPrc<>();

        System.out.println(functionPrc.compute(hi, t -> {
            return t.length();
        }));

		// compse和andThen的应用例子
        FunctionPrc<Integer,Integer> funcPrc = new FunctionPrc<>();

        System.out.println("compose:"+funcPrc.compute(3,value -> value*value,value->2*value));
        System.out.println("andThen:"+funcPrc.compute2(3,value -> value*value,value->2*value));
    }

    public R compute(T t, Function<T,R> func){
        return  func.apply(t);
    }

    public int compute(int a,Function<Integer,Integer> func1,Function<Integer,Integer> func2){
        return func1.compose(func2).apply(a);
    }

    public int compute2(int a,Function<Integer,Integer> func1,Function<Integer,Integer> func2){
        return func1.andThen(func2).apply(a);
    }
}

2.3 其他

其他的函数式接口大同小异

函数式接口函数描述符方法名称原始类型特化描述
PredicateT->booleanboolean test(T t)IntPredicate,LongPredicate, DoublePredicate接受一个参数返回一个boolean类型
ConsumerT->voidvoid accept(T t)IntConsumer,LongConsumer, DoubleConsumer接受参数无返回值
Function<T,R>T->RR apply(T t)IntFunction, IntToDoubleFunction, IntToLongFunction, LongFunction, LongToDoubleFunction, LongToIntFunction, DoubleFunction, ToIntFunction, ToDoubleFunction, ToLongFunction接受一个参数返回一个
Supplier()->TT get();BooleanSupplier,IntSupplier, LongSupplier, DoubleSupplier不接受参数返回值
UnaryOperatorT->Tstatic UnaryOperator identity() { return t -> t; }IntUnaryOperator, LongUnaryOperator, DoubleUnaryOperator
BinaryOperator(T,T)->TIntBinaryOperator, LongBinaryOperator, DoubleBinaryOperator接受一个参数返回和接受参数一样的数据类型结果
BiPredicate<L,R>(L,R)->boolean接受2个参数返回boolean
BiConsumer<T,U>(T,U)->voidObjIntConsumer, ObjLongConsumer, ObjDoubleConsumer接受2个参数不返回值
BiFunction<T,U,R>(T,U)->RToIntBiFunction<T,U>, ToLongBiFunction<T,U>, ToDoubleBiFunction<T,U>接受2个参数返回一个值

其他的接口例子

public class PridecatePrc {

    public static void main(String[] args) {

        List<Integer> list = Arrays.asList(1,2,3,4,5,6,7,8,9,10);

        PridecatePrc pridecatePrc = new PridecatePrc();

        // 找到集合中所有偶数
        pridecatePrc.conditionFilter(list,value -> value%2 == 0);
        System.out.println("------------");
        // 找到集合中所有的奇数
        pridecatePrc.conditionFilter(list,value -> value%2 != 0);
        System.out.println("------------");
        // 找到所有大于5的
        pridecatePrc.conditionFilter(list,value -> value > 5);
    }

    public void conditionFilter(List<Integer> list,Predicate<Integer> predicate){
        for (Integer i : list) {
            if(predicate.test(i)){
                System.out.print(i+" ");
            }
        }
    }
}


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

        Supplier<Apple> supplier = () -> new Apple();   // 此处可以使用工厂
        System.out.println(supplier.get().getColor());

        Supplier<Apple> supplier2 = Apple :: new;   // 构造方法引用
        Integer price  = supplier2.get().getPrice();
        if (price > 5) {
            System.out.println("苹果涨价了,好贵,现在已经每斤" + price);
        }

    }
}

更详细的例子可以参考:https://www.cnblogs.com/dgwblog/p/11739500.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值