如果我们有一个列表如下
Rollno name age address
====== ==== === =======
01 abc 11 pqr
02 stu 21 pqr
我们应该根据名称对此列表进行排序。如果学生的姓名相同,则根据年龄进行排序,如果年龄相同,则根据数字进行排序。 我被困在如何排序名称 我试过的代码是
public void sortData(List<Student> studentList) {
String a1=null;
String a2[] = null;
int i=0;
for (Iterator<Student> iter = list.listIterator(); iter.hasNext();) {
Student a = iter.next();
System.out.println(a1 = a.getStudentName());
}
System.out.println(a2);
}
这是卷号的打印列表,但我现在没有得到如何排序。
答案 0 :(得分:1)
使用Comparable和Collections.sort():
public class TestClass {
@Test
public void testSort() {
List<Student> list = new ArrayList<Student>();
list.add( new Student( "two", "4", "street7" ) );
list.add( new Student( "two", "4", "street6" ) );
list.add( new Student( "one", "1", "street3" ) );
list.add( new Student( "two", "2", "street5" ) );
Collections.sort( list );
assertEquals(
"[Student [name=one, age=1, adress=street3], " +
"Student [name=two, age=2, adress=street5], " +
"Student [name=two, age=4, adress=street6], " +
"Student [name=two, age=4, adress=street7]]",
list.toString()
);
}
public static class Student implements Comparable<Student> {
String name;
String age;
String adress;
public Student( String name, String age, String adress ) {
super();
this.name = name;
this.age = age;
this.adress = adress;
}
@Override
public int compareTo( Student o ) {
if ( o == null ) {
return -1;
}
int compare = name.compareTo( o.name );
if ( compare != 0 ) {
return compare;
}
compare = age.compareTo( o.age );
if ( compare != 0 ) {
return compare;
}
return adress.compareTo( o.adress );
}
@Override
public String toString() {
StringBuilder builder = new StringBuilder();
builder.append( "Student [name=" );
builder.append( name );
builder.append( ", age=" );
builder.append( age );
builder.append( ", adress=" );
builder.append( adress );
builder.append( "]" );
return builder.toString();
}
}
}