前几天听同事给我分享List的两种排序方式,于是就写了一个demo,分享给大家。
1、利用java.util.Collections.sort(List<Object> list, Comparator<? super Object> c)自带方法进行排序。
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
public class Test {
private String name;
private int score;
public Test(String name, int score) {
super();
this.name = name;
this.score = score;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getScore() {
return score;
}
public void setScore(int score) {
this.score = score;
}
public static void main(String[] args) {
List<Test> list = new ArrayList<Test>();
list.add(new Test("张三", 100));
list.add(new Test("李四", 98));
list.add(new Test("王五", 99));
list.add(new Test("赵六", 98));
list.add(new Test("马七", 89));
Collections.sort(list, new Comparator<Test>() {
@Override
public int compare(Test o1, Test o2) {
int i = o1.getScore() - o2.getScore();
return i;
}
});
for (Test tes : list) {
System.out.println("姓名:" + tes.getName() + ",分数:" + tes.getScore());
}
}
}
当用o1-o2时,是正序排列,当o2-o1时,是倒序排列。
运行结果:
姓名:马七,分数:89
姓名:李四,分数:98
姓名:赵六,分数:98
姓名:王五,分数:99
姓名:张三,分数:100
2、实现Comparable<Test>接口
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
public class Test implements Comparable<Test>{
private String name;
private int score;
public Test(String name, int score) {
super();
this.name = name;
this.score = score;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getScore() {
return score;
}
public void setScore(int score) {
this.score = score;
}
@Override
public int compareTo(Test o) {
int i = this.score - o.score;//正序排列
//int i = o.score - this.score;//倒序排列
return i;
}
public static void main(String[] args) {
List<Test> list = new ArrayList<Test>();
list.add(new Test("张三", 100));
list.add(new Test("李四", 98));
list.add(new Test("王五", 99));
list.add(new Test("赵六", 98));
list.add(new Test("马七", 89));
Collections.sort(list);
for (Test tes : list) {
System.out.println("姓名:" + tes.getName() + ",分数:" + tes.getScore());
}
}
}
运行结果:
姓名:马七,分数:89
姓名:李四,分数:98
姓名:赵六,分数:98
姓名:王五,分数:99
姓名:张三,分数:100