In Java 8 it’s possible to put static methods on interfaces. Why aren’t all of the Collector-related static methods on the Collector interface? Isn’t the old pattern of interface X
and class Xs
(such as Collection
/Collections
or Path
/Paths
) obsolete?
Static methods on interfaces are indeed a new tool in the toolbox. That means older tools might get used less often, but not that they’ll be thrown away. Sometimes it makes sense to put static methods on interfaces, and sometimes it still makes sense to put a bunch of static methods into a separate utility class. This is admittedly somewhat subjective.
In the case of the Collector
interface, the two static methods added in Java 8 (the of()
overloads) are very general. They allow one to create a new, independent collector from lambda expressions or from any existing method. On the other hand, the static methods on the Collectors
class create instances of ready-to-use collectors that are useful for specific purposes. This qualitative difference seemed significant enough to place the ready-to-use collectors into their own class.
In addition, there are three dozen methods that in the Collectors
class. Having them all together would have added a lot of clutter to the Collector
interface, which is fundamental and cohesive interface that benefits from having relatively few methods.
Leave a Reply