Guava入门第六章(Functions)

Functions详细介绍


package com.lvshihao.guava;

import com.google.common.base.*;

/**
 *@author: LVSHIHAO
 *@description: GUAVA Function detailed introduction
 * 和 JAVA 1.8 的 lambda 表达式类似
 */
public class FunctionsTest {

    public static void main(String[] args) {
        //define The Method Logic Of A Functional Interface
        Function<String,Integer> function=(v->{
            Preconditions.checkNotNull(v);
            return v.length();
        });

        System.out.println(function.apply("lvshihao"));
        process("lvshihao",new Handler.LengthDoubleHandler());
        System.out.println(Functions.toStringFunction().apply(new Object()));

        /**
         * use Guava Functions Functional Interface
         */
        Function<String,Double> compose=Functions.compose((Integer v1)->v1*3.0,(String input)->input.length());
        Double composeValue = compose.apply("lvshihao");
        System.out.println(composeValue);

        /**
         * use Guava Suppliers Functional Interface
         */
        Supplier<String> compose1 = Suppliers.compose(v -> v+"eee", () -> 6666);
        String s = compose1.get();
        System.out.println(s);
    }
    interface Handler<IN,OUT>{
        OUT handler(IN input);

        class LengthDoubleHandler implements Handler<String,Integer>{

            @Override
            public Integer handler(String input) {
                return input.length()*2;
            }
        }
    }

    private static void process(String text,Handler<String,Integer> handler){

        System.out.println(handler.handler(text));

    }
}

posted @ 2021-08-19 17:11  吕世昊  阅读(71)  评论(0编辑  收藏  举报