-1

The Stream.max() takes an argument of type Comparator, which contains the compare() method; The compare method takes two arguments and returns an int. So we can use a method to refer to Integer#compare() as an argument to the max() method; But Integer.compareTo() accepts only one parameter, which does not match the number of parameters of the compare() method, so why can it also be used as a parameter of max()?

that's my code:

Integer maxMenuTp = menuTpList.stream().max(Integer::compareTo);
Naman
  • 27,789
  • 26
  • 218
  • 353
Sunraise
  • 3
  • 1
  • 3
    `Integer::compareTo`, when implementing `Comparator`, is equivalent to `(a, b) -> a.compareTo(b)`. – Slaw Mar 26 '20 at 07:50
  • can you provide some more infomation, such as what your menuTpList looks like, or some more code, etc. – Xiao Yu Mar 26 '20 at 07:51
  • Related, if not a duplicate: [Java 8 stream max() function argument type Comparator vs Comparable](https://stackoverflow.com/q/55694015/6395627). – Slaw Mar 26 '20 at 08:08

1 Answers1

4

Integer::compareTo i.e. public int compareTo(Integer b) in Integer is an instance method, therefore it fits the Comparator functional interface by accepting one parameter as this, and the second as the method parameter.

Therefore (a, b) -> Comparator.compare(a, b) and (a, b) -> a.compareTo(b) are both acceptable as lambda parameters.

Kayaman
  • 72,141
  • 5
  • 83
  • 121