但这是一个如何做的示例程序 . 我假设您想先按名称排序,然后按日期排序 . 你可以把逻辑放在自定义比较器中 .
import java.util.*;
public class SortExample {
public static class Student {
public String name;
public String date;
public Student(String name, String date) {
this.name = name;
this.date = date;
}
}
public static class StudentComparator implements Comparator {
@Override
public int compare(Student s, Student t) {
int f = s.name.compareTo(t.name);
return (f != 0) ? f : s.date.compareTo(t.date);
}
}
public static void main(String args[]) {
ArrayList l = new ArrayList(Arrays.asList(
new Student ("x","2010-10-5"),
new Student ("z","2010-10-15"),
new Student ("y","2010-10-05"),
new Student ("x","2010-10-1")
));
System.out.println("Unsorted");
for(Student s : l) {
System.out.println(s.name + " " + s.date);
}
Collections.sort(l, new StudentComparator());
System.out.println("Sorted");
for(Student s : l) {
System.out.println(s.name + " " + s.date);
}
}
}
输出是:
Unsorted
x 2010-10-5
z 2010-10-15
y 2010-10-05
x 2010-10-1
Sorted
x 2010-10-1
x 2010-10-5
y 2010-10-05
z 2010-10-15
EDIT :这会对数组列表进行排序 . 如果您希望将其作为新列表,则必须先将其复制 .