我有一张地图,它将一个键存储为字符,将值存储为方法调用。 当我从地图中获取值时,将调用特定方法。
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;
}
如何修改源代码以返回字符串类型或任何其他类型?
答案 0 :(得分:2)
IntUnaryOperator
将int
和结果int
UnaryOperator<T>
将T
,结果T
(IntUnaryOperator
为UnaryOperator<Integer>
)Function<T,R>
将T
,结果R
(UnaryOperator<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中更改