最近有小伙伴们问小编List集合可以排序吗?今天动力节点java培训机构小编专门针对此问题对大家介绍,List集合是可以排序的,List集合排序有两种方法,下面就随小编一起看看List集合排序的两种方法是什么呢?
首先讲一下Comparable接口和Comparator接口,以及他们之间的差异。有助于Collections.sort()方法的使用。
1、Comparable自然规则排序
//在自定义类Student里面实现Comparable接口,并重写抽象方法compareTo(Student o);
//Collections.sort(集合);
先看一个简单的例子:
public static void main(String[] args) {
List
nums.add(3);
nums.add(5);
nums.add(1);
nums.add(0);
System.out.println(nums);
Collections.sort(nums);
System.out.println(nums);
输出结果:
[3, 5, 1, 0]
[0, 1, 3, 5]
稍微复杂的List里面放一个复杂的对象
package core.java.collection.collections;
public class User implements Comparable
private int score;
private int age;
public User(int score, int age){
super();
this.score = score;
this.age = age;
}
public int getScore() {
return score;
}
public void setScore(int score) {
this.score = score;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
@Override
public int compareTo(User o) {
int i = this.getAge() - o.getAge();//先按照年龄排序
if(i == 0){
return this.score - o.getScore();//如果年龄相等了再用分数进行排序
}
return i;
}
}
public static void main(String[] args) {
List
users.add(new User(78, 26));
users.add(new User(67, 23));
users.add(new User(34, 56));
users.add(new User(55, 23));
Collections.sort(users);
for(User user : users){
System.out.println(user.getScore() + "," + user.getAge());
}
}
输出结果:
55,23
67,23
78,26
34,56
我们会发现sort(List
2、Comparator专门规则排序(l临时排序)
//新建一个实现了Comparator接口的类,并重写抽象方法compare(Student o1, Student o2);
//Collections.sort(集合,实现了Comparator接口的类的实例化对象);
Collections提供的第二种排序方法sort(List
先看例子:
package core.java.collection.collections;
public class Students {
private int age;
private int score;
public Students(int age, int score){
super();
this.age = age;
this.score = score;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public int getScore() {
return score;
}
public void setScore(int score) {
this.score = score;
}
}
public static void main(String[] args) {
List
students.add(new Students(23, 100));
students.add(new Students(27, 98));
students.add(new Students(29, 99));
students.add(new Students(29, 98));
students.add(new Students(22, 89));
Collections.sort(students, new Comparator
@Override
public int compare(Students o1, Students o2) {
int i = o1.getScore() - o2.getScore();
if(i == 0){
return o1.getAge() - o2.getAge();
}
return i;
}
});
for(Students stu : students){
System.out.println("score:" + stu.getScore() + ":age" + stu.getAge());
}
}
输出结果:
score:89:age22
score:98:age27
score:98:age29
score:99:age29
score:100:age23
从上面的例子我们可以看出Students类没有实现Comparable
相关免费视频教程推荐
List集合可以排序视频教程下载:http://www.bjpowernode.com/xiazai/2486.html
你适合学Java吗?4大专业测评方法
代码逻辑 吸收能力 技术学习能力 综合素质
先测评确定适合在学习