Java中Comparator多级排序的实现
(2015-11-18 00:01:32)
标签:
comparator多级排序java |
分类: J2SE |
JDK里的Comparator方法为用户提供了自定义排序规则的接口,而我们在实际使用是一般也只是用了一个排序维度,本文介绍下多级或多个维度的排序需求下的接口实现。
Java代码
-
public
Class Employee { -
-
public int level; //级别 -
public int salary; //工资 -
public int years; //入职年数 -
-
}
下面这种肯定是不对的
Java代码
-
Comparator
cp_by_default = new Comparator(){ -
@Override -
public int compare(Employee a1, Employee a2) { -
int a = a2.level - a1.level; -
if(a > 0) -
return a; -
a = a2.salary - a1.salary; -
if(a > 0) -
return a; -
return a2.years - a1.years; -
} -
};
Java代码
-
package
net.oschina.tester; -
-
import
java.util.ArrayList; -
import
java.util.Collections; -
import
java.util.Comparator; -
import
java.util.List; -
-
-
public
class Employee { -
-
public static void main(String[] args) { -
List objs = new ArrayList(){{ -
add(new Employee(5,3,5000,2)); -
add(new Employee(1,9,10000,10)); -
add(new Employee(4,5,8000,6)); -
add(new Employee(2,9,12000,7)); -
add(new Employee(6,1,2000,1)); -
add(new Employee(3,5,8000,12)); -
}}; -
Collections.sort(objs, comparator); -
System.out.println("No\tLevel\tSalary\tYears\n============================="); -
for(Employee a : objs) -
System.out.printf("%d\t%d\t%d\t%d\n",a.id,a.level,a.salary,a.year); -
} -
-
public Employee(int id, int level, int salary, int year){ -
this.id = id; -
this.level = level; -
this.salary = salary; -
this.year = year; -
} -
-
public int id; -
public int level; -
public int salary; -
public int year; -
-
private final static Comparator comparator = new Comparator(){ -
@Override -
public int compare(Employee a1, Employee a2) { -
int cr = 0; -
int a = a2.level - a1.level; -
if(a != 0) -
cr = (a>0)?3:-1; -
else{ -
a = a2.salary - a1.salary; -
if(a != 0) -
cr = (a>0)?2:-2; -
else{ -
a = (int)(a2.year - a1.year); -
if(a != 0) -
cr = (a>0)?1:-3; -
} -
} -
return cr; -
} -
}; -
-
}