我必须按出生日期对一组人员对象进行排序,因此我创建了以下 pojo。
public class Person implements Comparable<Person> {
private long id;
private String name;
private Date birthDate;
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Date getBirthDate() {
return birthDate;
}
public void setBirthDate(Date birthDate) {
this.birthDate = birthDate;
}
@Override
public int compareTo(Person person) {
if (getBirthDate() == null || person.getBirthDate() == null)
return 0;
return getBirthDate().compareTo(person.getBirthDate());
}
}
Run Code Online (Sandbox Code Playgroud)
这完成了对出生日期进行排序的工作,但我的额外要求是按照最接近今天升序的出生日期对它们进行排序。因此,例如,如果今天是 10 月 11 日,那么生日将作为示例进行排序。
10月20
日11月5
日1月3日...
以我目前拥有的方式,因为年份是可比日期的一部分,日期显示从最古老的年份到最近的年份。
如何在没有年份的情况下对这些生日进行排序?
这完成了对出生日期进行排序的工作,但我的额外要求是按照最接近今天升序的出生日期对它们进行排序。例如,如果今天是 10 月 11 日,那么生日将作为示例进行排序
如果我理解你是对的,在排序时你不会考虑年份,例如 1975 还是它?。在我看来,您正在使用出生日记忆功能。但是,如果您根据 进行排序month and day,则以下comparedTo()功能应该会给您一些想法,以根据不包括年份的月份和日期进行比较:
class Person implements Comparable<Person>
{
Date birthDay;
static SimpleDateFormat formatter = new SimpleDateFormat("MMM dd, yyyy");
public Person(String birthDay) throws ParseException
{
this.birthDay = formatter.parse(birthDay);
}
@Override
public int compareTo(Person o) {
Calendar cal1 = Calendar.getInstance();
cal1.setTime(this.birthDay);
Calendar cal2 = Calendar.getInstance();
cal2.setTime(o.birthDay);
int month1 = cal1.get(Calendar.MONTH);
int month2 = cal2.get(Calendar.MONTH);
if(month1 < month2)
return -1;
else if(month1 == month2)
return cal1.get(Calendar.DAY_OF_MONTH) - cal2.get(Calendar.DAY_OF_MONTH);
else return 1;
}
}
Run Code Online (Sandbox Code Playgroud)
尝试使用以下代码测试:
List<Person>persons = new ArrayList<>();
persons.add(new Person("MAR 2, 2001"));
persons.add(new Person("JAN 7, 1972"));
persons.add(new Person("JAN 2, 1976"));
persons.add(new Person("MAR 4, 1985"));
Collections.sort(persons);
for(Person p : persons)
System.out.println(p.formatter.format(p.birthDay));
//Person.formatter is SimpleDateFormat with format "MMM dd, yyyy"
// in person class, i declared it as static
Run Code Online (Sandbox Code Playgroud)
输出:
Jan 02, 1976
Jan 07, 1972
Mar 02, 2001
Mar 04, 1985
Run Code Online (Sandbox Code Playgroud)
根据枢轴对列表进行排序,例如 OCT 11
我认为排序后,您可以将列表四舍五入,认为它是循环的。例如假设排序列表:
JAN 20, FEB 5, SEP 18, OCT 9, OCT 20, NOV 23
如果我们的枢轴OCT 11选择它的直接较大(大于枢轴的最小日期)日期, 则为OCT 20. 您只需使用for loop. 现在,我们只需要将它四舍五入,认为它是圆形的:
OCT 20, NOV 23 --> JAN 20, FEB 5, SEP 18, OCT 9
正式地,根据月份和i日期comparing找到我们的pivot的直接较大日期的索引(尝试使用compareTo示例),然后创建一个新列表,从索引开始插入元素iton-1然后0toi-1,这里n是出生的大小日期列表。
我希望这有帮助。
| 归档时间: |
|
| 查看次数: |
4665 次 |
| 最近记录: |