Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>Another good way of doing this that is a bit more flexible if there is more than one property of an object that you may wish to sort by is to use <a href="http://code.google.com/p/guava-libraries/" rel="nofollow noreferrer">Guava</a>'s <a href="https://google.github.io/guava/releases/snapshot/api/docs/com/google/common/collect/Ordering.html" rel="nofollow noreferrer">Ordering</a> class with its <code>onResultOf(Function)</code> option. This is ideally suited for sorting by properties since a <a href="http://guava-libraries.googlecode.com/svn/trunk/javadoc/com/google/common/base/Function.html" rel="nofollow noreferrer">Function</a> can be used to retrieve and return a specific property of an object. For a simple example, imagine a class <code>Person</code> with <code>String getFirstName()</code> and <code>String getLastName()</code> methods.</p> <pre><code>List&lt;Person&gt; people = ...; Collections.sort(people, Ordering.natural().onResultOf( new Function&lt;Person, String&gt;() { public String apply(Person from) { return from.getFirstName(); } })); </code></pre> <p>The above will sort the list by first name.</p> <p>To make it read nicer, you may want to define the functions you might want to use as <code>public static final</code> fields on the <code>Person</code> class. Then you could sort by last name like this:</p> <pre><code>Collections.sort(people, Ordering.natural().onResultOf(Person.GET_LAST_NAME)); </code></pre> <p>As a fun aside note, this will all be a lot easier in Java 8 with lambda expressions and method references. You'll be able to write something like this without having to define any clumsy anonymous inner classes or static final fields:</p> <pre><code>import static java.util.Comparator.comparing; ... people.sort(comparing(Person::getLastName)); </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload