java 8 - Why does Map<K,V> not extends Function<K,V>? -


while playing around new java 8 stream api got wondering, why not:

public interface map<k,v> extends function<k, v> 

or even:

public interface map<k,v> extends function<k, v>, predicate<k> 

it easy implement default methods on map interface:

@override default boolean test(k k) {     return containskey(k); }  @override default v apply(k k) {     return get(k); } 

and allow use of map in map method:

final mymagicmap<string, integer> map = new mymagichashmap<>(); map.put("a", 1); map.put("b", 2); map.put("c", 3); map.put("d", 4);  final stream<string> strings = arrays.stream(new string[]{"a", "b", "c", "d"}); final stream<integer> remapped = strings.map(map); 

or predicate in filter method.

i find significant proportion of use cases map construct or similar 1 - remapping/lookup function.

so, why did jdk designers not decide add functionality map during redesign java 8?

the jdk team aware of mathematical relationship between java.util.map data structure , java.util.function.function mapping function. after all, function named mapper in jdk 8 prototype builds. , stream operation calls function on each stream element called stream.map.

there discussion possibly renaming stream.map else transform because of possible confusion between transforming function , map data structure. (sorry, can't find link.) proposal rejected, rationale being conceptual similarity (and map purpose in common usage).

the main question is, gained if java.util.map subtype of java.util.function.function? there discussion in comments whether subtyping implies "is-a" relationship. subtyping less "is-a" relationships of objects -- since we're talking interfaces, not classes -- imply substitutability. if map subtype of function, 1 able this:

map<k,v> m = ... ; source.stream().map(m).collect(...); 

right away we're confronted baking in behavior of function.apply 1 of existing map methods. sensible 1 map.get, returns null if key isn't present. these semantics are, frankly, kind of lousy. real applications going have write own methods supply key-missing policy anyway, there seems little advantage of being able write

map(m) 

instead of

map(m::get) 

or

map(x -> m.getordefault(x, def)) 

Comments

Popular posts from this blog

Payment information shows nothing in one page checkout page magento -

tcpdump - How to check if server received packet (acknowledged) -