[英]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
和结果T
( IntUnaryOperator
是UnaryOperator<Integer>
)Function<T,R>
will take T
and result R
( UnaryOperator<T>
is Function<T,T>
) Function<T,R>
将采用T
和结果R
( UnaryOperator<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";
}
reference method
jusr forreference method
jusr 中更改了一个
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.