我正在从数据库中获取学生信息,
ArrayList<Student> studentList = session.createQuery("from Student order by Date").list();studentList包含名称、id、标记和日期。我想按姓名显示此数组列表,因为相同的学生姓名包含不同的日期。如何从arraylist中排序。Ex studentList值为
1 x 2010-10-01
2 y 2010-10-05
3 z 2010-10-15
1 x 2010-10-10
1 x 2010-10-17
2 y 2010-10-15
4 xx 2010-10-10我想把这个展示给
1 x 2010-10-01
1 x 2010-10-10
1 x 2010-10-17
2 y 2010-10-05
2 y 2010-10-15
3 z 2010-10-15
4 xx 2010-10-10并将其存储到另一个数组列表中
发布于 2011-10-20 17:48:40
有很多问题可以回答这个问题,比如:https://stackoverflow.com/questions/2784514/sort-arraylist-of-custom-objects-by-property
但这里有一个示例程序,说明了要做什么。我以为你想先按名字排序,然后再按日期排序。您可以将逻辑放在自定义比较器中执行此操作。
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<Student> {
@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<Student> l = new ArrayList<Student>(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:这将对数组列表进行原地排序。如果你想把它作为一个新的列表,你必须先复制它。
发布于 2011-10-20 17:15:22
您需要的方法是:
Collections.sort(List)
Collections.sort(List, Comparator)
如果您的Student类实现了Comparable接口,则可以使用第一种方法。另外,值得考虑的是,实际上您的数据是否应该存储在排序的数据结构中,比如SortedMap (例如,TreeMap实现)。
发布于 2011-10-20 17:46:43
我已经编写了一个框架来按地区敏感的顺序对对象的自然语言文本表示进行排序:
http://softsmithy.sourceforge.net/lib/docs/api/org/softsmithy/lib/text/Localizables.html
要么学生需要实现Localizable,要么您必须通过扩展Localizer来提供StudentLocalizer。
Maven:
<dependency>
<groupId>org.softsmithy.lib</groupId>
<artifactId>lib-core</artifactId>
<version>0.1</version>
</dependency> 下载:
http://sourceforge.net/projects/softsmithy/files/softsmithy/v0.1/
https://stackoverflow.com/questions/7833584
复制相似问题