Search code examples
javafunctional-interface

Should functional interfaces be called directly?


I built a few classes that implement functional interfaces so that they can be reused, these include Predicates, Functions, etc.

These work great when I pass a new instance into a collection stream, for example:

myList.stream().filter(new PrimeNumberPredicate())...

Today I found the usage of a predicate by creating and calling a predicate directly:

boolean result = new PrimeNumberPredicate().test(myData);

I find this code a bit verbose, and I'd like to ask if there is another way to write this so that I could do the test without explicitly calling test() on a single object.


Solution

  • I wouldn't do either. The fun of functional interfaces is that you don't have to explicitly implement any particular interface, nor create useless objects. All you need is a method that does what you want and you can bend it to your functional will.

    Define the predicate function staticly:

    class PrimeNumbers {
        public static boolean isPrime(int number) {
            ...
        }
    }
    

    Then use it in a stream like so:

    myList.stream().filter(PrimeNumbers::isPrime)...
    

    Non-functional code like your co-worker's could skip instantiating an object and call the function directly:

    boolean result = PrimeNumbers.isPrime(myData);
    

    This has the advantage of letting you name the class and method naturally, rather than "predicate" or "test" or "apply".