Ordering
is Guava’s fluent Comparator class and implements Comparator interface. It can be used to build complex comparators and apply them to collections of objects.
Okay, so let’s getting started. Firstly, we declared a String
type List:
1 | private List<String> locations = Lists.newArrayList( |
We will use this locations variable later.
natural()
Use natural ordering for comparatable types. such as number from small to large. date from start to end. It is static method.
1 | // use natural comparator, such as a -> z |
sortedCopy(Iterable)
Return a sorted copy of the specified elements as a List.
We create a customized Ordering
that sorted by the length of element from small to large. Let’s get the code:
1 | private Ordering<String> getCustomzieStringOrder() { |
Order the locations list with our new customize Ordering
:
1 | Ordering<String> byLengthOrdering = getCustomzieStringOrder(); |
isOrdered(Iterable)
Return a Boolean variable that can describe the Iterable if sorted.
1 | // will return false. because the locations array is not sorted. |
reverse()
Return the reverse Ordering
.
1 | // reverse customize comparator. |
nullsFirst()
Return an Ordering
that will put the null object at the first.
1 | // add null object to the locations array. |
nullsLast()
Return an Ordering
that will put the null object at the last.
1 | // null object will at last. |
compound()
Returns an Ordering
which uses the specified Comparator to “break ties.”
1 | // the "AAAAAAAA" length is equal to "Cheng du" length. (8 characters) |
onResultOf(Fuction)
Returns an Ordering which orders values by applying the function to them and then comparing the results using the original Ordering.
Declaring a Foo class:
1 | public class Foo { |
Declaring a new List with Foo class type:
1 | private List<Foo> fooList = Lists.newArrayList( |
Define a new function that will return an customized Ordering
:
1 | private Ordering<Foo> getNaturalFooOrder() { |
greatestOf(Iterable iterable, int k)
Returns the k greatest elements of the specified iterable, according to this ordering, in order from greatest to least. Not necessarily stable.
1 | // the result will be [23+abc] |
leastOf(Iterable iterable, int k)
Returns the k least elements of the specified iterable, according to this ordering, in order from least to greatest. Not necessarily stable.
1 | // the result will be [null+abc, 10+abc] |
min(Iterable)
Returns the minimum element of the specified Iterable. Throws a NoSuchElementException if the Iterable is empty.
1 | // the result will be null+abc |
max(Iterable)
Returns the maximum element of the specified Iterable. Throws a NoSuchElementException if the Iterable is empty.
1 | // the result will be 23+abc |