Java的List集合按照对象的多个属性排序public class Employee {
private int level;
private int salary;
private int years;
public int getLevel() {
return level;
}
public void setLevel(int level) {
this.level = level;
}
public int getSalary() {
return salary;
}
public void setSalary(int salary) {
this.salary = salary;
}
public int getYears() {
return years;
}
public void setYears(int years) {
java集合排序怎么实现
}
@Override
public String toString() {
return "Employee [level=" + level + ", salary=" + salary + ", years="
+ years + "]";
}
}
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
setContentView(R.layout.activity_main);
List<Employee> list = new ArrayList<Employee>();
Employee e = new Employee();
e.setLevel(1);
e.setSalary(300);
e.setYears(4);
list.add(e);
e = new Employee();
e.setLevel(1);
e.setSalary(500);
e.setYears(4);
list.add(e);
e = new Employee();
e.setLevel(2);
e.setSalary(500);
e.setYears(4);
list.add(e);
e = new Employee();
e.setLevel(1);
e.setSalary(300);
e.setYears(5);
list.add(e);
//        Collections.sort(list, new Comparator<Employee>() {
/
/            public int compare(Employee e2, Employee e1) {
//                int a = e1.getLevel() - e2.getLevel();
//                if (a != 0) {
//                    return a > 0 ? -1 : 1;
//                }
//                a = e1.getSalary() - e2.getSalary();
//                if (a != 0) {
//                    return a > 0 ? -1 : 1;
//                }
//                a = e1.getYears() - e2.getYears();
//                return a > 0 ? -1 : 1;
/
/            }
//        });
Collections.sort(list, new Comparator<Employee>() {            public int compare(Employee e1, Employee e2) {                int a = e1.getLevel() - e2.getLevel();
if (a != 0) {
return a > 0 ? 1 : -1;
}
a = e1.getSalary() - e2.getSalary();
if (a != 0) {
return a > 0 ? 1 : -1;
}
a = e1.getYears() - e2.getYears();
return a > 0 ? 1 : -1;
}
});
//  Employee [level=2, salary=500, years=4]
//  Employee [level=1, salary=500, years=4]
//  Employee [level=1, salary=300, years=5]
//  Employee [level=1, salary=300, years=4]
// Employee [level=1, salary=300, years=4]
// Employee [level=1, salary=300, years=5]
// Employee [level=1, salary=500, years=4]
// Employee [level=2, salary=500, years=4]
/
/          [level=1, salary=300, years=4]
//          [level=1, salary=300, years=5]
//          [level=1, salary=500, years=4]
//          [level=2, salary=500, years=4]
for (Employee em : list) {
System.out.println(em);
}
}
}

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。