Before we dive into more examples utilizing Guava ordering, it is important to understand how to read chaining. Chaining is where you wrap or you call multiple ordering variations together. From the guava ordering explained page we can look at this example:
When you read Ordering chains, you read right to left instead of left to right. Above we can read it as: for each element to order we will apply a function then place nulls first in the list and we want it by the natural order. There is one exception to the rule and that is when you compound multiple comparator together. A suggestion the guava folks have is to avoid intermixing compound calls with chain calls.
For our second series of examples we created two objects: an address object and enum that represents the US states. We created an arraylist of states and initialized it with random addresses.
Since most of our real life situations we are looking to order a collection of objects, lets look at a few ways Ordering helps us.
If we want to order a collection by an object field, we can create an Ordering instance that looks at the object by creating a guava function and passing it to onResultOf. By creating a function that accepts an address and returns a string that represents a city, we can create a comparator that will sort a list of addresses by city.
We can construct a Ordering class by calling Ordering.from and passing String.CASE_INSENSITIVE_ORDER comparator that orders String objects by the compareToIgnoreCase. Then creating a function that accepts an address object and returns a string for address line we will pass it to onResultOf. Next calling sortedCopy and passing the list of address we sort address by address line.
Enums by default are ordered in which they are declared but if we want to declare them in a specific order, in this instance lets order them by midwest states. We can specify an Ordering class by calling Ordering.explicit and list the order which we want the collection sorted. We can create an list of enums of type state and then call Collections.sort. This is kind of neat way to order enums as many folks use enums values in drop down lists.
In this snippet we will sort addresses by State enum in a specific order. We will read right to left, we will return a sorted copy of addresses then we will say Address.onState which is a function that accepts an address and returns a State enum. Then calling State.stateOrder we can specify an specific order, so what we are saying is we want to sort the addresses by the State enum in a specific order.
Compound
In this snippet we will show how to compound or combine multiple comparators first by creating an Ordering object from String.CASE_INSENSITIVE_ORDER and then call the compound or add the byLength comparator.
Thanks for joining in today's level up lunch, I hope you got a bit more out of the Ordering class that guava provides.