I'm using Java to create an interactive application to ask users for thei开发者_如何学JAVAr date of birth. At the minute I have a date being read in and stored as a String in the form (dd-mm-yyyy). Now there are mutliple people being stored in an arraylist, all with different dates of birth. Whats the best way to sort the arraylist depending on their dates of birth?
Kind Regards
Are you storing Person
objects in the list or dates? If storing dates (java.util.Date
), you can simply sort the list and it should work out fine for you. If you store Person
objects, you can pass in a custom Comparator
which would be used by the sorting utility.
References:
- Sorting a list
- Sorting a list based on custom requirements
Start by converting the String to a java.util.Date. Dates have different semantics for sorting than Strings do.
Once you do that, write a Comparator to do the job for you. Pass it along with your List to Collections.sort().
Store the dates in Date
objects. They are sortable out of the box. Or, if it's sufficient to keep Strings, change the date format from
dd-mm-yyyy
to
yyyy-mm-dd
for sorting.
Collections.sort(collection, comparator);
implement your custom comparator (interface java.util.Comparator
) that compares your object according to date of birth.
There is a link already provided in stack over flow:http://stackoverflow.com/questions/1517745/sorting-on-last-name
精彩评论