欢迎光临
我们一直在努力

Java集合排序Collections.sort接口Comparator使用

示例如下:

package org.4spaces.michael;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

public class SrTest {
    public static void main(String[] args) {
        SrTest srTest = new SrTest();
        Student s1 = srTest.new Student();
        Student s2 = srTest.new Student();
        s1.setAge(1);
        s2.setAge(2);
        List<Student> list = new ArrayList();
        list.add(s1);
        list.add(s2);
        Collections.sort(list, new Comparator<Student>() {
            @Override
            public int compare(Student o1, Student o2) {
                return o2.getAge()-o1.getAge();
            }
        });
        for (Student s:list){
            System.out.println(s.getAge());
        }
    }

    class Student {
        private int age;

        public Student() {
        }

        public int getAge() {
            return age;
        }

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

打印结果

2
1

上述代码实现了学生对象的年龄的降序排列。

赞(0)
未经允许不得转载:Ddmit » Java集合排序Collections.sort接口Comparator使用

评论 抢沙发

登录

找回密码

注册