Since Date implements Comparable , it has a compareTo method just like String. I wanted to sort an ArrayList of custom objects by one of their properties: a Date object ( getStartDay() ). From your code, it looks like your Comparator is already parameterized with .
Comparator to sort a Java object based on its property value. In this tutorial we will see how to sort an ArrayList of Objects by property using comparable and comparator . How do you sort a list of Objects in Java is one of the frequently asked coding questions in Java interviews and surprisingly not every Java programmers know .
What if you want to sort based on two (or more) properties in the class. Consider an ArrayList that stores country names as String objects. To sort the ArrayList, you need to simply call the Collections.
As soon as I started writing my answer I saw Soheil Hassas Yeganeh answer which. Well, Java provides a very good API to sort a list of objects, You can implement a Comparator and pass that comparator to Collections. A List l may be sorted as follows.
If the List consists of String elements, it will be sorted into alphabetical order.
Keine Kommentare:
Kommentar veröffentlichen
Hinweis: Nur ein Mitglied dieses Blogs kann Kommentare posten.