Haobo_X
Haobo_X

Reputation: 77

My confusion with Java Lambda expression

I know that Java's Lambda expression can replace a parameter whose type is an Interface (only contains one method), but why I can execute code like this:

String[] myArray = new String[3];
Arrays.sort(myArray, (a, b) -> {return b.compareTo(a);});

In this case, the lambda expression (a, b) -> {return b.compareTo(a);} replaces an object of Comparator interface, but Comparator interface has more than one method, why?

Upvotes: 0

Views: 155

Answers (3)

Kevin Krumwiede
Kevin Krumwiede

Reputation: 10308

You can do this because Comparator only declares one method for which there is no default implementation. (You may notice that it redeclares equals without an implementation, but this is only to document the effect of overriding it in a Comparator. A default implementation is inherited from Object, as discussed here.)

Upvotes: 4

Stewart
Stewart

Reputation: 18313

From the JavaDocs for java.util.Comparator:

Functional Interface:

This is a functional interface and can therefore be used as the assignment target for a lambda expression or method reference.

java.util.Comparator is annotated with @FunctionalInterface which is:

used to indicate that an interface type declaration is intended to be a functional interface as defined by the Java Language Specification. Conceptually, a functional interface has exactly one abstract method.

Upvotes: 2

53248832
53248832

Reputation: 11

The comparator interface contains only 1 method: compare(...) Because of this it is a functional interface which can be used with lambdas.

Upvotes: 0

Related Questions