Reputation: 77
I'm trying to map a String to Lambda Expressions. The expressions take a variable(map) and either return false or run a getOrDefault on the given map variable. But for some reason, I am getting errors.
Map<String, Runnable> order_function = new HashMap<>();
order_function.put("AlternativesValues", (Map x) -> { return false; });
order_function.put("AlternativesConstituent", (Map x) -> { x.getOrDefault("orderCloseCons", false); });
Upvotes: 0
Views: 1517
Reputation: 597
If they mean to be constants, you can use enum
like below.
enum OrderFunctions {
ALTERNATIVES_VALUES("AlternativesValues", map -> false),
ALTERNATIVES_CONSTITUENT("AlternativesConstituent", map -> map.getOrDefault("orderCloseCons", false));
private final String name;
private final Function<Map<String, Boolean>, Boolean> orderFunction;
OrderFunctions(String name, Function<Map<String, Boolean>, Boolean> orderFunction) {
this.name = name;
this.orderFunction = orderFunction;
}
public String getName() {
return name;
}
public Function<Map<String, Boolean>, Boolean> getOrderFunction() {
return orderFunction;
}
}
and you can use it like below.
OrderFunctions.ALTERNATIVES_CONSTITUENT.getOrderFunction().apply(someMap);
Upvotes: 0
Reputation: 44466
The Runnable
doesn't return anything. If you expand the lambda to the anonymous class implementation, you will see the void
is the return type:
Runnable runnable = new Runnable() {
@Override
public void run() {
// implementation
}
};
This is in conflict with your lambda> (Map x) -> { return false; }
.
Since you need an expression which takes a Map
and returns a boolean
, then you need Predicate<Map<? ,Boolean>>
(keep the wildcard ?
or replace it with whatever is needed):
Map<String, Predicate<Map<? ,Boolean>>> order_function = new HashMap<>();
order_function.put("AlternativesValues", x -> false);
order_function.put("AlternativesConstituent", map -> map.getOrDefault("orderCloseCons", false));
Upvotes: 2
Reputation: 3134
perhaps you wanted to use Function
instead of Runnable
:
Map<String, Function<Map<String, Boolean>, Boolean>> order_function = new HashMap<>();
order_function.put("AlternativesValues", x -> false);
order_function.put("AlternativesConstituent", map -> map.getOrDefault("orderCloseCons", false));
//...
boolean alternativesValues = order_function.get("AlternativesValues").apply(someMap);
Upvotes: 0