Java中 Collections.sort()方法

本文详细介绍了Java中Collections.sort()方法的使用,通过示例代码展示了如何进行升序和降序排序,以及如何对自定义类型的集合按特定规则排序。通过匿名内部类简化了代码实现。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

本着简单的原则,我们来实现用Collection的静态方法sort()的讲解,其中,只需要将实现Collection的集合(LinkedList,ArrayList,HashSet,TreeSet)等直接写入sort()方法中就可以自动按照升序排序,那么如果想要降序怎么办,或者有是有是自定义的类型,想按照自己的想法排序怎么办?
代码如下

class Student{
    public int score;
    public int age;
    Student(int score,int age){
        this.age=age;
        this.score=score;
    }
}

这是我们定义的类,要使用sort()方法,本着简单的原则,我们使用匿名内部类来简化代码

Collections.sort(myList,new Comparator<Student>(){
            public int compare(Student o1,Student o2){
                int result=o1.score-o2.score;
                if(result==0){
                    result=o2.age-o1.age;
                }
                return result;
            }
        });

这句代码直接实现排序,意思是,按照成绩升序排序,如果成绩相同,按照年龄降序排序。注意Comparator别忘了写<Student>的泛型
所有代码

package cn.Try;
import java.util.Collections;
import java.util.Comparator;
import java.util.LinkedList;
public class Main{
    public static void main(String[] args){
        Student one=new Student(70,17);
        Student two=new Student(70,16);
        Student three=new Student(70,30);
        Student four=new Student(70,13);
        Student five=new Student(70,17);
        LinkedList<Student> myList=new LinkedList<Student>();
        myList.add(one);
        myList.add(two);
        myList.add(three);
        myList.add(four);
        myList.add(five);
        Collections.sort(myList,new Comparator<Student>(){
            public int compare(Student o1,Student o2){
                int result=o1.score-o2.score;
                if(result==0){
                    result=o2.age-o1.age;
                }
                return result;
            }
        });
        for(int i=0;i<myList.size();i++){
            System.out.println(myList.get(i).score+"  "+myList.get(i).age+"岁");
        }
    }
}
class Student{
    public int score;
    public int age;
    Student(int score,int age){
        this.age=age;
        this.score=score;
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值