欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

java自带的Collections.sort实现对象集合的排序(正序或者倒序)

程序员文章站 2022-03-21 21:13:44
...

1.实体类 

package com.test.model;

public class Student {
	private Integer id;    //学生id
	private String userName;    //学生姓名
	private Integer age;    //学生年龄
	
	

	public Student(Integer id, String userName, Integer age) {
		super();
		this.id = id;
		this.userName = userName;
		this.age = age;
	}

	public Integer getId() {
		return id;
	}

	public void setId(Integer id) {
		this.id = id;
	}

	public String getUserName() {
		return userName;
	}

	public void setUserName(String userName) {
		this.userName = userName;
	}

	public Integer getAge() {
		return age;
	}

	public void setAge(Integer age) {
		this.age = age;
	}

	@Override
	public String toString() {
		return "Student [id=" + id + ", userName=" + userName + ", age=" + age ]";
	}

}

2.排序 

        Student stu1 = new Student(1, "小马", 10);
		Student stu2 = new Student(2, "小马2", 10);
		Student stu3 = new Student(3, "小马3", 30);
		Student stu4 = new Student(4, "小马4", 40);
		Student stu5 = new Student(5, "小马5", 50);

		List<Student> studentList = new ArrayList<Student>();
		studentList.add(stu1);
		studentList.add(stu2);
		studentList.add(stu3);
		studentList.add(stu4);
		studentList.add(stu5);

		System.out.println("排序前--:" + studentList.toString());
        
        //studentList:排序的对象
        //Student:学生对象
		Collections.sort(studentList, new Comparator<Student>() {
            
			@Override
			public int compare(Student o1, Student o2) {
                // 从大到小(按照学生id)
				//return o2.getId().compareTo(o1.getId());

                // 从小到大(按照学生id)
				//return o1.getId().compareTo(o2.getId());

				// 从大到小(按照年龄)
				return o2.getAge().compareTo(o1.getAge());

			}

		});

		System.out.println("倒序排序后--:" + studentList.toString());

 

相关标签: java 排序