Search code examples
performancejava-8functional-interface

When to use functional interfaces in JAVA 8


I have project in java7 which i am trying to convert to java8 now.

In that i have a code which calls a method which i have converted to Java 8 like below.

JAVA 7:

Long id=10;
Student student= Student.findById(id);

JAVA 8

Long id=10;
Function<Long,Student> f=Student::findById;
f.apply(id);

Now my question doesn't it make any sense to convert the method calls like these to JAVA 8.

If so What is difference between the above code in JAVA 7 and JAVA 8.

Can anyone Please clarify this???


Solution

  • In your Java 7 example you invoke findById() in line 2 and assign the result to student. By using method references in your Java 8 code snipped you first save a reference to the method findById() in f and invoke that method in line 3. Method references give you the ability to delay the invocation of methods. In combination with Streams you can achieve laziness this way.

    For you example it doesn't make sense to use method references as they don't give you any benefit. If you want to pass the method reference to an other function or delay the invocation it could make sense to use method references. Otherwise you just clutter your code with explicit apply calls.

    I recommend to look at Java 8 introductions that feature examples. I read the book Functional Programming in Java and can only recommend it.