如何在java中按名称对ArrayList值进行排序 [英] How to sort ArrayList values by name in java

查看:73
本文介绍了如何在java中按名称对ArrayList值进行排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am getting student information from database,

ArrayList<Student> studentList = session.createQuery("from Student order by Date").list();

studentList包含姓名,ID,标记,按日期。我想按姓名显示这个arraylist,因为同一个学生名称包含不同的日期。
如何从arraylist中对此进行排序。
Ex studentList值

the studentList contains name , id ,marks, by date. I want to display this arraylist by name, becase the same student name contains different date. How to sort this from arraylist. Ex studentList value is

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

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

and store this to another array list

推荐答案

很多问题要看这个答案,例如:
https://stackoverflow.com/questions/2784514/sort-arraylist-of-custom-objects-by-property

There are plenty of questions to look at that answer this, such as: https://stackoverflow.com/questions/2784514/sort-arraylist-of-custom-objects-by-property

但这是一个示例程序,该怎么做。我假设你想先按名字排序,然后按日期排序。您可以在自定义比较器中输入逻辑。

But here is an example program of what to do. I assumed you wanted to sort by name first, and then date. You can put logic to do that in the custom comparator.

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

编辑:这会对数组列表进行排序。如果你想把它作为新的清单,你必须先复制它。

EDIT: This sorts the array list in place. You'd have to copy it first if you want it as a new list.

这篇关于如何在java中按名称对ArrayList值进行排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆