排序日期 - 用户输入
我正在使用 Java 创建一个交互式应用程序来询问用户的出生日期。目前,我正在读取一个日期并将其存储为表单中的字符串(dd-mm-yyyy)。现在有多个人存储在一个数组列表中,每个人都有不同的出生日期。根据出生日期对数组列表进行排序的最佳方法是什么?
亲切的问候
I'm using Java to create an interactive application to ask users for their 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
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
您是否在列表或日期中存储
Person
对象?如果存储日期(java.util.Date
),您可以简单地对列表进行排序,它应该适合您。如果您存储Person
对象,则可以传入排序实用程序将使用的自定义Comparator
。参考文献:
根据定制要求
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 storePerson
objects, you can pass in a customComparator
which would be used by the sorting utility.References:
based on custom requirements
首先将字符串转换为 java.util.Date。日期的排序语义与字符串不同。
完成此操作后,编写一个比较器来为您完成这项工作。将其与您的列表一起传递给 Collections.sort()。
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().
将日期存储在
Date
对象中。它们开箱即可分类。或者,如果保留字符串就足够了,请将日期格式从 更改为 来
进行排序。
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 fromto
for sorting.
Collections.sort(集合、比较器);
实现您的自定义比较器(接口
java.util.Comparator
),根据出生日期比较您的对象。Collections.sort(collection, comparator);
implement your custom comparator (interface
java.util.Comparator
) that compares your object according to date of birth.stack over flow中已经提供了一个链接:http://stackoverflow.com/questions/1517745/sorting-on-last-name
There is a link already provided in stack over flow:http://stackoverflow.com/questions/1517745/sorting-on-last-name