Reputation: 31
I want to create a read-only Map backed by a guava Function. I have a function which provides the value, given a key.
Function f = new Function() {
public Object apply(final Object key) {
return ...;
}
};
Map m = mapBasedOnFunction(f); // is this possible with Guava?
m.get(some key); // the value is provided by the function
Is this possible with Guava?
I understand that iteration, size(), ... will not work, which is not required here. Actually, I only need the get() function to be functional.
Thank you very much.
Upvotes: 3
Views: 318
Reputation: 568
I'm not really sure what your are trying to accomplish here but - like George mentioned - something like this should work:
public class FunctionMap extends HashMap<Object, Object> {
private Function<Object, Object> function;
public FunctionMap(Function<Object, Object> function) { this.function = function; }
@Override
public Object get(Object key) { return function.apply(key); }
}
Upvotes: 0
Reputation: 27735
You can do this with Maps.toMap
but you need to supply an Iterable
of keys.
Function f = ...
Set keys = ...
Map map = Maps.toMap( keys, f );
Without the keys the map can't really handle .size()
or .entrySet()
.
Upvotes: 4
Reputation: 2525
AFAIK the inverse is possible. You use Functions.forMap() and give it a Map which this call turns into a Function that can work as a mapping table.
I'm not sure you can do that with Guava.
Upvotes: 1