Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

java 8 - store method in HashMap and get return value from method in map

I want to store methods pointer in map to execute them based on a string value. Аrom what I found, I can use Map<String, Runnable> to do it, but the problem is I want to get the return value from the method.

Say I have something like this:

private Map<String, Runnable> timeUnitsMap = new HashMap<String, Runnable>() {{
    timeUnitsMap.put("minutes", () -> config.getMinutesValues());
}}

The method config.getMinutesValues() is from another class.

How can I do int value = timeUnitsMap.get("minutes").run(); or to store something else in the map (instead of Runnable) in order to get the value from the function in the map?

like image 327
Ofek Agmon Avatar asked Jan 05 '23 22:01

Ofek Agmon


1 Answers

Runnable doesn't return a value. You should use Supplier or Callable instead.

The primary difference between Supplier and Callable is that Callable allows you to throw a checked exception. You then have to handle the possibility of that exception everywhere you use the Callable. Supplier is probably simpler for your use case.

You would need to change your Map<String, Runnable> to a Map<String, Supplier<Integer>>. The lambda function itself wouldn't need changing.

@assylias pointed out in a comment that you could also use Map<String, IntSupplier>. Using an IntSupplier avoids boxing your int as an Integer.

like image 110
Sam Avatar answered Jan 07 '23 11:01

Sam