Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>You can make your object comparable:</p> <pre><code>public static class MyObject implements Comparable&lt;MyObject&gt; { private Date dateTime; public Date getDateTime() { return dateTime; } public void setDateTime(Date datetime) { this.dateTime = datetime; } @Override public int compareTo(MyObject o) { return getDateTime().compareTo(o.getDateTime()); } } </code></pre> <p>And then you sort it by calling:</p> <pre><code>Collections.sort(myList); </code></pre> <p>However sometimes you don't want to change your model, like when you want to sort on several different properties. In that case, you can create comparator on the fly:</p> <pre><code>Collections.sort(myList, new Comparator&lt;MyObject&gt;() { public int compare(MyObject o1, MyObject o2) { return o1.getDateTime().compareTo(o2.getDateTime()); } }); </code></pre> <p>However, the above works only if you're certain that dateTime is not null at the time of comparison. It's wise to handle null as well to avoid NullPointerExceptions:</p> <pre><code>public static class MyObject implements Comparable&lt;MyObject&gt; { private Date dateTime; public Date getDateTime() { return dateTime; } public void setDateTime(Date datetime) { this.dateTime = datetime; } @Override public int compareTo(MyObject o) { if (getDateTime() == null || o.getDateTime() == null) return 0; return getDateTime().compareTo(o.getDateTime()); } } </code></pre> <p>Or in the second example:</p> <pre><code>Collections.sort(myList, new Comparator&lt;MyObject&gt;() { public int compare(MyObject o1, MyObject o2) { if (o1.getDateTime() == null || o2.getDateTime() == null) return 0; return o1.getDateTime().compareTo(o2.getDateTime()); } }); </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