1

I am trying to wrap my head around Java 8 concepts. In the context of Method references, I would like to know how does the stream filter method which accepts a 'Predicate predicate' object in my case can also accept a static method in same class. Example below.

public class App 
{
    public static void main( String[] args )
    {
        List<Integer> intList = Arrays.asList(1,2,3,4,5);
        intList.stream().filter( e -> e > 3 ).forEach(System.out::println);

        intList.stream().filter( App::filterNosGrt3 ).forEach(System.out::println);

    }


    public static boolean filterNosGrt3(Integer no)
    {
        if(no>3)
            return true;
        else
            return false;
    }
}

What confuses me is unlike the Lambda, which is an object in itself, the static method has no object attached to it. So how does it satisfy the filter method here.

Thanks

HariJustForFun
  • 521
  • 2
  • 8
  • 17

1 Answers1

2

When you write

intList.stream().filter( App::filterNosGrt3 ).forEach(System.out::println);

you're effectively writing:

intList.stream().filter(e -> App.filterNosGrt3(e)).forEach(System.out::println);

It's just a feature of method references. From the Java method references tutorial:

You use lambda expressions to create anonymous methods. Sometimes, however, a lambda expression does nothing but call an existing method. In those cases, it's often clearer to refer to the existing method by name. Method references enable you to do this; they are compact, easy-to-read lambda expressions for methods that already have a name.

...

The method reference Person::compareByAge is semantically the same as the lambda expression (a, b) -> Person.compareByAge(a, b). Each has the following characteristics:

  • Its formal parameter list is copied from Comparator<Person>.compare, which is (Person, Person).
  • Its body calls the method Person.compareByAge.
Community
  • 1
  • 1
T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875