集合List存放的数据,默认是按照放入时的顺序存放的,比如依次放入ABCD,则取得时候也是ABCD的顺序,实际场景中,我们需要安装自定义的规则对List元素进行排序。
Collections对List集合中的数据进行排序,需要用到工具类Collections,其中的sort()方法
public static void main(String[] args) {
List<Integer> nums = new ArrayList<Integer>();
nums.add(3);
nums.add(5);
nums.add(1);
nums.add(0);
System.out.println(nums);
Collections.sort(nums);
System.out.println(nums);
}
List集合对象按照属性排序
public class Test {
public static void main(String[] args) {
List<Student> list = new ArrayList<Student>();
//创建3个学生对象,年龄分别是20、19、21,并将他们依次放入List中
Student s1 = new Student();
s1.setAge(20);
Student s2 = new Student();
s2.setAge(19);
Student s3 = new Student();
s3.setAge(21);
list.add(s1);
list.add(s2);
list.add(s3);
System.out.println("排序前:"+list);
Collections.sort(list, new Comparator<Student>(){
/* int compare(Student o1, Student o2) 返回一个基本类型的整型,
* 返回负数表示:o1 小于o2,
* 返回0 表示:o1和o2相等,
* 返回正数表示:o1大于o2。
*/
public int compare(Student o1, Student o2) {
//按照学生的年龄进行升序排列
if(o1.getAge() > o2.getAge()){
return 1;
}
if(o1.getAge() == o2.getAge()){
return 0;
}
return -1;
}
});
System.out.println("排序后:"+list);
}
}
当然对象的属性可以多个,比如按年龄升序,按成绩降序等
public class User implements Comparable<User>{
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<User> users = new ArrayList<User>();
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());
}
}
对List集合内的元素进行顺序、排序、随机排序
public class Test {
List list = new LinkedList();
public static void main(String[] args) {
List list = new LinkedList();
for ( int i = 0 ; i < 9 ; i ++ ) {
list.add( " a " + i);
}
Collections.sort(list); // 顺序排列
System.out.println(list);
Collections.shuffle(list); // 混乱的意思
System.out.println(list);
Collections.reverse(list); // 倒序排列
System.out.println(list);
System.out.println(Collections.binarySearch(list, " a5 " )); // 折半查找
}
}
参考博客:http://blog.csdn.net/lifuxiangcaohui/article/details/41543347