简体   繁体   English

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

[英]expression to get different return type in java lambda expressions

I am having a map which stores a key as a character and value as an method call.我有一个映射,它将键存储为字符,将值存储为方法调用。 when I get the value from the map the particular method gets invoked.当我从地图中获取值时,会调用特定方法。

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));

Where function1 is as follows,其中function1如下,

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

How can I modify the source code to return an string type or any other type?如何修改源代码以返回字符串类型或任何其他类型?

  • IntUnaryOperator will take int and result int IntUnaryOperator将接受int并产生int
  • UnaryOperator<T> will take T and result T ( IntUnaryOperator is UnaryOperator<Integer> ) UnaryOperator<T>将取T和结果TIntUnaryOperatorUnaryOperator<Integer>
  • Function<T,R> will take T and result R ( UnaryOperator<T> is Function<T,T> ) Function<T,R>将采用T和结果RUnaryOperator<T>Function<T,T>

So you need Function<Integer,String> :所以你需要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";
}
  • I also change one in reference method jusr for我也在reference method jusr 中更改了一个

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM