如何在java中按名称对ArrayList值进行排序

lak*_*hmi 1 java arraylist

我从数据库中获取学生信息,

ArrayList<Student> studentList = session.createQuery("from Student order by Date").list();
Run Code Online (Sandbox Code Playgroud)

studentList包含按日期的名称,ID,标记.我想通过名字显示这个arraylist,因为相同的学生姓名包含不同的日期.如何从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
Run Code Online (Sandbox Code Playgroud)

我想显示这个

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
Run Code Online (Sandbox Code Playgroud)

并将其存储到另一个数组列表中

Ben*_*ict 6

有很多问题要看这个答案,例如: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);
    }
  }
}
Run Code Online (Sandbox Code Playgroud)

输出是:

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
Run Code Online (Sandbox Code Playgroud)

编辑:这将数组列表排序.如果您希望将其作为新列表,则必须先将其复制.


Ada*_*ski 5

您需要的方法是:

Collections.sort(List<T>)

Collections.sort(List<T>, Comparator<? super T>)

如果您的Student类实现了Comparable接口,则可以使用第一种方法.作为旁注,值得考虑的是,实际上您的数据是否应存储在已排序的数据结构中SortedMap(例如TreeMap实现).