0

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?

Stewart
  • 17,616
  • 8
  • 52
  • 80
Haobo_X
  • 77
  • 1
  • 8

3 Answers3

4

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

Kevin Krumwiede
  • 9,868
  • 4
  • 34
  • 82
2

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.

Stewart
  • 17,616
  • 8
  • 52
  • 80
0

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

53248832
  • 11
  • 1