Function优化大量的if else(案例一)

Function(Function )可以看作转换型函数,有一个输入型参数T和返回型参数R。

package com;

import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
import java.util.function.Function;

public class Function1Test {
    private static Map<String, Function<String,String>> map = new HashMap();
    public static void main(String[] args) {
        init();
        String type = "a";
//        if(type.equals("a")){
//            func01("A","B");
//        } else if(type.equals("b")){
//            func02("C","D");
//        }else if(type.equals("c")){
//            func03("E","F");
//        }else if(type.equals("d")){
//            func03("G","H");
//        }
        map.get(type).apply("A");
    }

    private static void init() {
        map.put("a",Function1Test::func01);
        map.put("b",Function1Test::func02);
        map.put("c",Function1Test::func03);
        map.put("d",Function1Test::func04);
    }

    public static String func01(String... str){
        System.out.println("================func01==============="+ Arrays.toString(str));
        return "func01";
    }

    public static String func02(String... str){
        System.out.println("================func02==============="+ Arrays.toString(str));
        return "func02";
    }

    public static String func03(String... str){
        System.out.println("================func03==============="+ Arrays.toString(str));
        return "func03";
    }

    public static String func04(String... str){
        System.out.println("================func04==============="+ Arrays.toString(str));
        return "func04";
    }
}

你可能感兴趣的:(随笔,java)