Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

Java Introducing Lambdas

Michael Anderson
Michael Anderson
3,971 Points

Not sure I understand how methods accept Lambdas as parameters

In looking at the documentation for Collections (https://docs.oracle.com/javase/8/docs/api/java/util/Collections.html), it seems that Collections.sort is an overloaded method that can either take a List or a List and a Comparator. I'm having a hard time wrapping my mind around how the compiler can look at the Lambda expression and treat it as something that implements the Comparator interface.

How does the compiler know that the expression we provide essentially implements the abstract method of the required interface? Are there only certain interfaces that are used as a method parameter that can be replaced by Lambda expressions?

I know this isn't a very clear/well-put question, but I'm kinda lost on the mechanics of how this works. I appreciate your help!

1 Answer

Benjamin Barslev Nielsen
Benjamin Barslev Nielsen
18,958 Points

lambdas can only be used with functional interfaces. Look at What-is-a-functional-interface for a brief description of what a functional interface is. The link also explains why Comparator is a functional interface.

To check if an interface in the API is functional, look for the @FunctionalInterface annotation. In the API for Comparator you can see:

@FunctionalInterface
public interface Comparator<T>

which describes that Comparator is a functional interface and therefore can be used with a lambda.

Michael Anderson
Michael Anderson
3,971 Points

Thank you! I think I get it now. The "What is a Functional Interface" page you linked to is a good explanation.

So, to make sure I understand it correctly, functional interfaces must have exactly one abstract method. In the case of Comparator, which seems to have two declared abstract methods (compare and equals), the equals method corresponds to a method that Comparator (and any other class) would otherwise implicitly inherit from Object, so it doesn't count, so to speak.