in java, use String::length for Comparator.comparing()

落爺英雄遲暮 提交于 2019-12-06 10:41:28

String::length is a method reference. Using it is equivalent to

Comparator.comparing(s -> s.length())

So it compares strings by comparing their length.

TL;DR: You are passing a method reference

Java 8 introduces lambda syntax to the Java language, this is a small part of that, it allows you to pass a method as a lambda.

So you call the method Comparator.comparing, this requires a "key extractor" function that takes an object from the Collection<T> and returns some object of a type U extends Comparable<? super U>.

The method String.length returns an Integer (when boxed) and an Integer is comparable to another Integer. So the call Comparator.comparing(String::length) returns a Comparator<String> that:

  • takes a pair of String, s1, s2
  • calls l1 = s1.length and l2 = s2.length
  • returns l1.compareTo(l2)

So, Why there is no parenthesis?

Because you are passing a method reference. This method will be called later on an as yet undefined instance. Notice that length is not static on String so String.length() would not compile.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!