ArrayList集合存储学生对象并排序

需求:

ArrayList集合存储学生对象,使用Collections对ArrayList集合进行排序,排序要求:年龄从小到大,年龄相同时,按照姓名字母顺序排序。

//测试类

import java.util.*;

public class work{
    public static void main(String[] args){
        //创建ArrayList集合对象
        ArrayList<Student> list = new ArrayList<Student>();
        //存储学生对象
        list.add(new Student("林青霞",30));
        list.add(new Student("王宝强",33));
        list.add(new Student("风清扬",33));
        list.add(new Student("橙留香",10));
        //使用Collections方法对ArrayList集合进行排序
        Collections.sort(list, new Comparator<Student>() {
            @Override
            public int compare(Student o1, Student o2) {
                int num1 = o1.getAge() - o2.getAge();
                int num2 = num1 == 0? o1.getName().compareTo(o2.getName()):num1;
                return num2;
            }
        });
        //用加强for循环进行遍历
        for(Student s:list){
            System.out.println(s.getName()+","+s.getAge());
        }
    }
}

//学生类

public class Student {
    private String name;
    private int age;

    public Student() {
    }

    public Student(String name,int age) {
        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;
    }
}

结果:

本人新手菜鸡一枚,请大佬们多多指教。

经验分享 程序员 微信小程序 职场和发展