前言
Java.util包中的List接口继承了Collection接口,用来存放对象集合,所以对这些对象进行排序的时候,要么让对象类自己实现同类对象的比较,要么借助比较器进行比较排序。
学生实体类,包含姓名和年龄属性,比较时先按姓名升序排序,如果姓名相同则按年龄升序排序。
第一种:实体类自己实现比较
(实现comparable接口:public interface Comparable ,里面就一个方法声明:public int compareTo(T o);)
示例代码:
public class Student implements Comparable{
private String name;
private int age;
public Student() {
super();
// TODO Auto-generated constructor stub
}
public Student(String name, int age) {
super();
this.name = name;
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
@Override
public int compareTo(Student o) {
// TODO Auto-generated method stub
int flag = this.name.compareTo(o.name);
if(flag == 0) {
flag = this.age - o.age;
}
return flag;
}
}
然后利用List类的sort(Comparator super E> c)方法或java.util.Collections工具类的sort(List list) (其实里面就一句:list.sort(null);)进行排序:
List students = new ArrayList();
students.add(new Student("a",10));
students.add(new Student("b",12));
students.add(new Student("b",11));
students.add(new Student("ac",20));
students.sort(null);
//Collections.sort(students);
结果:
a 10
ac 20
b 11
b 12
第二种:借助比较器进行排序。
示例代码:
public class Student {
private String name;
private int age;
public Student() {
super();
// TODO Auto-generated constructor stub
}
public Student(String name, int age) {
super();
this.name = name;
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
}
比较器java.util.Comparator类是一个接口(public interface Comparator ),包含int compare(T o1, T o2);等方法:
我们的比较器要实现该接口并实现compare方法:
private class StudentComparator implements Comparator {
@Override
public int compare(Student o1, Student o2) {
// TODO Auto-generated method stub
int flag = o1.getName().compareTo(o2.getName());
if(flag == 0) {
flag = o1.getAge() - o2.getAge();
}
return flag;
}
}
比较的时候可以利用List的sort(Comparator super E> c)方法(或者java.util.Collections工具类的sort(List list, Comparator super T> c)方法)进行排序。
List students = new ArrayList();
students.add(new Student("a",10));
students.add(new Student("b",12));
students.add(new Student("b",11));
students.add(new Student("ac",20));
Test t = new Test();
students.sort(t.new StudentComparator());
//Collections.sort(students, t.new StudentComparator());
for(Student student : students) {
System.out.println(student.getName()+" "+student.getAge());
}
结果跟第一种方法一样:
a 10
ac 20
b 11
b 12
总结
以上就是关于Java中对List进行排序的全部内容了,希望本文的内容对大家的学习或者工作能带来一定的帮助,如果有疑问大家可以留言交流。