This week's book giveaway is in the Jobs Discussion forum.
We're giving away four copies of Java Interview Guide and have Anthony DePalma on-line!
See this thread for details.
The moose likes Features new in Java 8 and the fly likes Java 8 Functional Interfaces Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login

Win a copy of Java Interview Guide this week in the Jobs Discussion forum!
JavaRanch » Java Forums » Java » Features new in Java 8
Bookmark "Java 8 Functional Interfaces" Watch "Java 8 Functional Interfaces" New topic

Java 8 Functional Interfaces

Joe Harry
Ranch Hand

Joined: Sep 26, 2006
Posts: 10033

In the recent days, I have been working extensively with Scala and I was eagerly looking forward using Java again and Java 8 seems to be promising with a lot of new features. I heard a lot about functional interfaces in Java 8, but never had the time to get into it. What exactly is it? Is it the interface that we write and tell to the compiler through annotations to treat them differently than the traditional interfaces in Java? I would be interested to know more.

SCJP 1.4, SCWCD 1.4 - Hints for you, Certified Scrum Master
Did a rm -R / to find out that I lost my entire Linux installation!
Stephan van Hulst

Joined: Sep 20, 2010
Posts: 4642

A functional interface is an interface that has only one method. Methods that take the interface as their parameter can then be passed a lambda instead of an object reference.

The @FunctionalInterface annotation is comparable to the @Override annotation. It explains to the compiler what you're trying to do, and the compiler will help you by making sure what you're trying to do is what happens.

If you don't use the @Override annotation, the compiler will not complain if you accidentally end up writing a method that doesn't override the one declared in the super-type. This can lead to problems.

With @FunctionalInterface, you tell the compiler that the interface you're writing should be able to have lambda "instances", instead of traditional anonymous instances. If you accidentally add a second method to the interface, the compiler will complain.

A functional interface will still be a functional interface without the annotation.

For instance, Comparator is now a functional interface. Instead of doing this:
You can now do this:
Actually it's even better to do this:

The mind is a strange and wonderful thing. I'm not sure that it will ever be able to figure itself out, everything else, maybe. From the atom to the universe, everything, except itself.
I agree. Here's the link:
subject: Java 8 Functional Interfaces
It's not a secret anymore!