表达式在java lambda表达式中获取不同的返回类型

时间:2017-10-27 10:40:43

标签: java lambda java-8

我有一张地图,它将一个键存储为字符,将值存储为方法调用。 当我从地图中获取值时,将调用特定方法。

Map<Character, IntUnaryOperator> commands = new HashMap<>();
commands.put('a', number -> funtion1(number) );
commands.put('b', number -> funtion1(number) );

char cmd = 'a';
IntUnaryOperator result=  commands.get(cmd);

System.out.println(" Return value is "+result.applyAsInt(101));

其中function1如下,

public static int funtion1(int number){
    System.out.println("hello");
    return number;
}

如何修改源代码以返回字符串类型或任何其他类型?

1 个答案:

答案 0 :(得分:2)

  • IntUnaryOperatorint和结果int
  • UnaryOperator<T>T,结果TIntUnaryOperatorUnaryOperator<Integer>
  • Function<T,R>T,结果RUnaryOperator<T>Function<T,T>

所以你需要Function<Integer,String>

public static void main(String[] args) throws ParseException {
    Map<Character, Function<Integer, String>> commands = new HashMap<>();
    commands.put('a', Guitar::funtion1); // method reference
    commands.put('b', number -> funtion1(number));

    char cmd = 'a';
    Function<Integer, String> result = commands.get(cmd);                 // Function
    System.out.println("Return value is " + result.apply(55));            // 55 bar
    System.out.println("Return value is " + commands.get('b').apply(32)); // 32 bar
}

public static String funtion1(int text) {
    System.out.println("hello");
    return text + " bar";
}
  • 我还在reference method jusr中更改