Member-only story
Effective Java! Favor the Use of Standard Functional Interfaces
With lambdas as part of the Java language more possible implementations have opened up. Where before we may have used an alternate pattern such as maybe the Template Method Pattern where a subclass overrides a method to specialize the behavior of the superclass, we can now use a factory method that takes a lambda that serves as the specialization function.
Let’s look at another example, LinkedHashMap. This can serve as a cache by overriding the removeEldestEntry
which gets invoked on each put
operation with the oldest item and which, when it returns true
, removes the oldest entry. For example, if we wanted to limit our map to 100 entries we could write something like:
protected boolean removeEldestEntry(Map.Entry<K,V> eldest) {
return size() > 100;
}
This method works fine but if it was built today it may be cleaner to pass a lambda to fulfill this purpose. So let’s think through what this map would need to take. It would of course take Map.Entry<K,V>
just like our removeEldestEntry
method. It also needs a reference to the map itself since it calls the size
method. Finally we need to consider the return type which in this case would be boolean
. So putting this all together we would get:
@FunctionalInterface
interface EldestEntryRemovalFunction<K,V> {
boolean remove(Map<K,V> map, Map.Entry<K,V> eldest);
}
This interface will work great, it’s exactly what we need. The question is is this necessary…