关于排序html
Guava的链式比较器java
例子git
assertTrue(byLengthOrdering.reverse().isOrdered(list));app
梗概函数
Ordering是Guava的链式比较器类,能够被用做构造复杂的比较器,并应用到collection对象。this
它的本质就仅仅是一个特殊的比较器实例。Ordering仅仅是执行一些依赖一个比较器的方法(譬如 Collections.max),而且把这些方法做为实例的的方法使用。Ordering类提供一些方法去调整和增强已经存在的比较器。google
怎样建立一个Orderingspa
普通的orderings由下面的静态方法建立。code
Methodhtm |
Description |
将能比较的对象按照天然顺序排序 |
|
使用toString()返回的字符串按字典顺序进行排序 |
|
使用一个已经存在的比较器 |
可是,去建立一个Ordering 更通常的方法是彻底跳过Comparator,直接去继承一个Ordering抽象类。
链式比较
1 Ordering<String> byLengthOrdering = new Ordering<String>() { 2 public int compare(String left, String right) { 3 return Ints.compare(left.length(), right.length()); 4 } 5 };
给予一个Ordering就能被包装,去得到派生的Orderings.下面是一些常常用到的变体方法。
Method |
Description |
返回一个顺序相反的Ordering. |
|
返回一个Ordering.,非空值优先输出,其他和最初的Ordering同样 |
|
当第一个比较器比较相等时使用第二个比较器。 |
|
Returns an Ordering that orders iterables lexicographically by their elements. 返回一个比较器,按照字典顺序遍历它的元素 |
|
返回一个比较器,它将函数应用到它的元素,而后按照最初的比较器将元素排序。 |
譬如,当你想要一个能将下面的类比较的比较器。。。
1 class Foo { 2 @Nullable String sortedBy; 3 int notSortedBy; 4 }
它能处理空的sortedBy。这儿是一种创建在链式方法的解决方案。
1 Ordering<Foo> ordering = Ordering.natural().nullsFirst().onResultOf(new Function<Foo, String>() { 2 public String apply(Foo foo) { 3 return foo.sortedBy; 4 } 5 });
当读到一个链式Ordering.的时候,从右往左看。上面的例子对Foo的实例排序是按照查找他们的属性值sortedBy,首先移动非空值到顶部,而后对他们的其他值进行排序。从后往前看是由于每个链式调用都是包装前一个Ordering 成为一个新的Ordering 。
(从后向前见解则的特例:如果链条中有compound,从左向后读。为了不迷惑,不要将包含 compound的调用和别的链式调用混合在一块儿。)
太长的链式不容易理解,咱们建议像例子那样将链式限制在3个回调。即便如此,你仍能够像Function 的实例那样经过分割出中间对象来简化链式。
1 Ordering<Foo> ordering = Ordering.natural().nullsFirst().onResultOf(sortKeyFunction);
关于应用
Guava提供许多方法去利用ordering 处理和检查值或者集合。咱们在下面列出如下一些常常用到的。
Method |
Description |
See also |
Returns the k greatest elements of the specified iterable, according to this ordering, in order from greatest to least. Not necessarily stable. |
||
Tests if the specified Iterable is in nondecreasing order according to this ordering. |
||
Returns a sorted copy of the specified elements as a List. |
||
Returns the minimum of its two arguments according to this ordering. If the values compare as equal, the first argument is returned. |
||
Returns the minimum of its arguments according to this ordering. If there are multiple least values, the first is returned. |
||
Returns the minimum element of the specified Iterable. Throws a NoSuchElementException if theIterable is empty. |