1.简单类型:
Collections.sort(list, new Comparator<String>(){
public int compare(int o1, int o2) {
return o1 - o2;
}
});
Collections.sort(list, new Comparator<String>(){
public int compare(String o1, String o2) {
return o1.length() - o2.length();
}
});
2.复杂类型(对象):
Collections.sort(list, new Comparator<Emp >(){
public int compare(Emp o1, Emp o2) {
return o1.getSalary() - o2.getSalary();
}
});
3.举个栗子:(根据学生成绩等级排序,A、B、C、D,把等级转换成字符的ASCII值进行排序)
public static void main(String[] args) {
List<Sutdent> list = new ArrayList<>();
Sutdent sutdent1 = new Sutdent();
sutdent1.setGrade("B");
list.add(sutdent1);
Sutdent sutdent2 = new Sutdent();
sutdent2.setGrade("A");
list.add(sutdent2);
for (Sutdent sutdent : list) {
System.out.println("排序前:" + sutdent.getGrade());
}
// list排序
Collections.sort(list, new Comparator<Sutdent>() {
@Override
public int compare(Sutdent s1, Sutdent s2) {
String grade1 = s1.getGrade();
String grade2 = s2.getGrade();
int num1 = 0;
int num2 = 0;
if (StringUtils.isNotBlank(grade1) && StringUtils.isNotBlank(grade2)) { // 判空
char[] chars1 = grade1.toCharArray();
for (char c : chars1) {
num1 += (int)c;
}
char[] chars2 = grade2.toCharArray();
for (char c : chars2) {
num2 += (int)c;
}
System.out.println("num1:" + num1);
System.out.println("num2:" + num2);
return num1 - num2;
} else {
return 0;
}
}
});
for (Sutdent sutdent : list) {
System.out.println("排序后:" + sutdent.getGrade());
}
}