Java 按两个属性对对象排序
假设我有一个学生列表:Java 按两个属性对对象排序,java,comparator,comparable,Java,Comparator,Comparable,假设我有一个学生列表:ArrayList student=new ArrayList()。学生班级如下所示: public class Student { String name; int age; String hobby; //getter and Setter methods below } 我想按名字对列表排序,但如果名字相等,我想按年龄排序。如何在Java中实现这一点 有了这个,我已经可以按名称排序了: public class MyComparat
ArrayList student=new ArrayList()代码>。学生班级如下所示:
public class Student {
String name;
int age;
String hobby;
//getter and Setter methods below
}
我想按名字对列表排序,但如果名字相等,我想按年龄排序。如何在Java中实现这一点
有了这个,我已经可以按名称排序了:
public class MyComparator implements Comparator<Student>{
@Override
public int compare(Student o1, Student o2) {
if(o1.getName() > o2.getName()){
return 1;
}
else if(o1.getName() < o2.getName())
{
return -1;
}
else{
return 0;
}
}
}
公共类MyComparator实现Comparator{
@凌驾
公共整数比较(学生o1,学生o2){
如果(o1.getName()>o2.getName()){
返回1;
}
else if(o1.getName()
因此,如果他们有相同的名字,我如何在年龄之后对其进行排序?
最后,我想做收集。排序(学生、MyComparator comp)
对列表进行排序。这应该可以:
public class StudentsComparator implements Comparator<Student> {
@Override
public int compare(Student s1, Student s2) {
final int nameComparison = s1.getName().compareToIgnoreCase(s2.getName());
if (nameComparison != 0) {
return nameComparison;
}
return Integer.compare(s1.getAge(), s2.getAge());
}
}
这应该起作用:
public class StudentsComparator implements Comparator<Student> {
@Override
public int compare(Student s1, Student s2) {
final int nameComparison = s1.getName().compareToIgnoreCase(s2.getName());
if (nameComparison != 0) {
return nameComparison;
}
return Integer.compare(s1.getAge(), s2.getAge());
}
}
返回o1.getAge()-o2.getAge()的可能重复项
而不是返回0代码>?您应该检查年龄,而不是返回0。我的问题与您所写的文章几乎相同,但我需要它作为两个属性。可能重复返回o1.getAge()-o2.getAge()
而不是返回0代码>?您应该检查年龄,而不是返回0。我的问题与您写的文章几乎相同,但我需要它的两个属性。谢谢这就是我想要的:)谢谢这就是我想要的:)