Friday 17 November 2017

lambda - Static Method References Java 8





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 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



Answer




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 href="http://docs.oracle.com/javase/tutorial/java/javaOO/methodreferences.html"
rel="nofollow noreferrer">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.compare, which is (Person,
    Person)
    .

  • Its body calls the method
    Person.compareByAge.




No comments:

Post a Comment

php - file_get_contents shows unexpected output while reading a file

I want to output an inline jpg image as a base64 encoded string, however when I do this : $contents = file_get_contents($filename); print &q...