Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>There are plenty of questions to look at that answer this, such as: <a href="https://stackoverflow.com/questions/2784514/sort-arraylist-of-custom-objects-by-property%20sort%20arraylist%20of%20objects">https://stackoverflow.com/questions/2784514/sort-arraylist-of-custom-objects-by-property</a></p> <p>But here is an example program of what to do. I assumed you wanted to sort by name first, and then date. You can put logic to do that in the custom comparator.</p> <pre><code>import java.util.*; public class SortExample { public static class Student { public String name; public String date; public Student(String name, String date) { this.name = name; this.date = date; } } public static class StudentComparator implements Comparator&lt;Student&gt; { @Override public int compare(Student s, Student t) { int f = s.name.compareTo(t.name); return (f != 0) ? f : s.date.compareTo(t.date); } } public static void main(String args[]) { ArrayList&lt;Student&gt; l = new ArrayList&lt;Student&gt;(Arrays.asList( new Student ("x","2010-10-5"), new Student ("z","2010-10-15"), new Student ("y","2010-10-05"), new Student ("x","2010-10-1") )); System.out.println("Unsorted"); for(Student s : l) { System.out.println(s.name + " " + s.date); } Collections.sort(l, new StudentComparator()); System.out.println("Sorted"); for(Student s : l) { System.out.println(s.name + " " + s.date); } } } </code></pre> <p>Output of this is:</p> <pre><code>Unsorted x 2010-10-5 z 2010-10-15 y 2010-10-05 x 2010-10-1 Sorted x 2010-10-1 x 2010-10-5 y 2010-10-05 z 2010-10-15 </code></pre> <p><strong>EDIT</strong>: This sorts the array list in place. You'd have to copy it first if you want it as a new list.</p>
 

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