1、编写实现类
package com.abcd; public class Person{ private String name; private int age; private int salary; public Person() { } public Person(String name, int age, int salary) { this.name = name; this.age = age; this.salary = salary; } 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; } public int getSalary() { return salary; } public void setSalary(int salary) { this.salary = salary; } @Override public String toString() { return "Person{" + "name='" + name + '\'' + ", age=" + age + ", salary=" + salary + '}'; } }
2、编写测试方法
package com.abcd; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.List; public class PersonTest { public static void main(String[] args){ List<Person> people = new ArrayList<>(); people.add(new Person("AAA",20,100)); people.add(new Person("BBB",48,109)); people.add(new Person("CCC",30,109)); System.out.println(people); Collections.sort(people, new Comparator<Person>() { @Override public int compare(Person o1, Person o2) { //salary降序 int flag= o2.getSalary()- o1.getSalary(); if (flag==0){ //年龄升序 return o1.getAge()-o2.getAge(); }else { return flag; } } }); System.out.println(people); } }
3、运行结果
[Person{name='AAA', age=20, salary=100}, Person{name='BBB', age=48, salary=109}, Person{name='CCC', age=30, salary=109}] [Person{name='CCC', age=30, salary=109}, Person{name='BBB', age=48, salary=109}, Person{name='AAA', age=20, salary=100}]
每天进步一点点
个人意见,仅供参考