背景:排序方法,按照部门Id和薪资排序。方法没有返回值,对参数集合进行排序。排序方式是true: 按照部门Id升序薪资升序排序;排序方式是false:按照部门Id升序薪资降序排序
实质:根据Java中的对象进行排序
实现思路:实体类实现Comparator接口,并且在排序的类继承实体类,排序的方法中重写compare方法
代码实现:
实体类:
package com.wonders;
import java.util.Comparator;
/**
* 职员类
*
* @author DELL
*
*/
public class Employee implements Comparator<Employee>{
private String name;// 姓名
private Long salary;// 薪资
private int departmentId;// 部门ID
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Long getSalary() {
return salary;
}
@Override
public String toString() {
return "Employee [name=" + name + ", salary=" + salary + ", departmentId=" + departmentId + "]";
}
public void setSalary(Long salary) {
this.salary = salary;
}
public int getDepartmentId() {
return departmentId;
}
public void setDepartmentId(int departmentId) {
this.departmentId = departmentId;
}
@Override
public int compare(Employee o1, Employee o2) {
return 0;
}
}
升序排序类:
package com.wonders;
/**
* 升序排序
* @author DELL
*
*/
public class SortObjectAsc extends Employee{
public int compare(Employee o1,Employee o2){
if (o1.getDepartmentId() > o2.getDepartmentId()) {
return 1;
}else if (o1.getDepartmentId() < o2.getDepartmentId()) {
return -1;
}else {
return 0;
}
}
}
降序排序类:
package com.wonders;
/**
* 降序排序
* @author DELL
*
*/
public class SortObjectDesc extends Employee{
public int compare(Employee o1,Employee o2){
if (o1.getDepartmentId() < o2.getDepartmentId()) {
return 1;
}else if (o1.getDepartmentId() > o2.getDepartmentId()) {
return -1;
}else {
return 0;
}
}
}
公用方法:
/**
* 根据boolean值来对员工信息进行升降排序
* @param list
* @param flag ture按照id升序,false按照id降序
* @return
*/
public static List<Employee> sortMember(List<Employee> list,boolean flag){
if (flag == true) {
Collections.sort(list, new SortObjectAsc());
}else if (flag == false) {
Collections.sort(list, new SortObjectDesc());
}
return list;
}
测试类中相关代码:
List<Employee> employeesList = new ArrayList<Employee>();
Employee e1 = new Employee();
e1.setName("zhangsan1");
e1.setSalary(6000L);
e1.setDepartmentId(1);
employeesList.add(e1);
Employee e2 = new Employee();
e2.setName("zhangsan2");
e2.setSalary(7000L);
e2.setDepartmentId(2);
employeesList.add(e2);
Employee e3 = new Employee();
e3.setName("zhangsan3");
e3.setSalary(8000L);
e3.setDepartmentId(3);
employeesList.add(e3);
Employee e11 = new Employee();
e11.setName("zhangsan1");
e11.setSalary(7000L);
e11.setDepartmentId(1);
employeesList.add(e11);
Employee e22 = new Employee();
e22.setName("zhangsan2");
e22.setSalary(8000L);
e22.setDepartmentId(2);
employeesList.add(e22);
Employee e33 = new Employee();
e33.setName("zhangsan3");
e33.setSalary(9000L);
e33.setDepartmentId(3);
employeesList.add(e33);
System.out.println(DateUtils.sortMember(employeesList, true));
System.out.println(DateUtils.sortMember(employeesList, false));