Java 集合排序多个项目
我目前正在尝试按姓氏、名字、出生日期、ssn对我的对象进行排序。但从逻辑上讲,我只能得出姓氏,然后才是名 有什么建议吗Java 集合排序多个项目,java,Java,我目前正在尝试按姓氏、名字、出生日期、ssn对我的对象进行排序。但从逻辑上讲,我只能得出姓氏,然后才是名 有什么建议吗 public int compareTo(Doctor o) { int result = this.lastName.compareTo(o.lastName()); return result == 0 ?this.firstName.compareTo(((Doctor) o).firstName()):result; } 按姓氏进行第一次排序。如
public int compareTo(Doctor o)
{
int result = this.lastName.compareTo(o.lastName());
return result == 0 ?this.firstName.compareTo(((Doctor) o).firstName()):result;
}
按姓氏进行第一次排序。如果排序值为
0
,则按firstname排序。如果结果为0
,则按出生日期排序,依此类推。当然,您将有多个return
语句,但可读性要高得多
您可能知道,结果值0
意味着这两个值相等。在您的用例中,这将导致额外的排序,而不是简单地返回值
编辑:下面的其他答案对此提供了确切的实现。对lastname进行第一次排序。如果排序值为
0
,则按firstname排序。如果结果为0
,则按出生日期排序,依此类推。当然,您将有多个return
语句,但可读性要高得多
您可能知道,结果值0
意味着这两个值相等。在您的用例中,这将导致额外的排序,而不是简单地返回值
编辑:下面的其他答案对此提供了确切的实现。嵌套的if是实现此功能的更好选择
public int compareTo(Doctor o){
int result = this.lastName.compareTo(o.lastName());
if(result==0){
result = this.firstName.compareTo(o.firstName());
if(result==0){
result = this.dob.compareTo(o.dob());
if(result==0){
....
}
}
}
return result;
}
嵌套if是实现此功能的更好选择
public int compareTo(Doctor o){
int result = this.lastName.compareTo(o.lastName());
if(result==0){
result = this.firstName.compareTo(o.firstName());
if(result==0){
result = this.dob.compareTo(o.dob());
if(result==0){
....
}
}
}
return result;
}
您可以使用以下选项:
public int compareTo(Doctor o)
{
int result = this.lastName.compareTo(o.lastName());
if (result != 0)
return result;
result = this.firstName.compareTo(o.firstName());
if (result != 0)
return result;
result = this.birthDate.compareTo(o.birthDate());
if (result != 0)
return result;
return this.ssn.compareTo(o.ssn());
}
您可以使用以下选项:
public int compareTo(Doctor o)
{
int result = this.lastName.compareTo(o.lastName());
if (result != 0)
return result;
result = this.firstName.compareTo(o.firstName());
if (result != 0)
return result;
result = this.birthDate.compareTo(o.birthDate());
if (result != 0)
return result;
return this.ssn.compareTo(o.ssn());
}
正如你可能已经意识到的,这是一种“责任链”。所以我建议你这个案子的模式
如果()…s正如您可能已经意识到的那样,这是一种“责任链”,它将避免您编写太多的内容。所以我建议你这个案子的模式 它将避免您编写过多的if()…s