今天遇到的一个问题List集合的多字段排序问题。对于一个对象,它有多个属性值,可能会根据不同的属性值对集合有个排序。
对集合的排序,主要是用到的是Collections.sort(List<T>, Comparator<? super T>)方法,或者是List.sort(Comparator<? super T> c)两个方法,里面实现了compare()方法。
int compare(T o1,
T o2)比较用来排序的两个参数。根据第一个参数小于、等于或大于第二个参数分别返回负整数、零或正整数。
在前面的描述中,符号 sgn(expression) 表示 signum 数学函数,根据 expression 的值为负数、0 还是正数,该函数分别返回 -1、0 或 1。
也比较简单,源码如下:
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
public class TestListSort {
public static void main(String[] args) {
List<Person> list = new ArrayList<Person>();
int ages[] = new int[] { 21, 17, 8, 29, 23, 31, 14, 37, 20, 15, 26 };
String names[] = new String[] { "account", "absort", "action", "a",
"advices", "adjust", "back", "abstract", "afraid", "boy", "act" };
for (int i = 0; i < ages.length; i++) {
Person person = new Person(names[i], ages[i]);
list.add(person);
}
// Comparator comparator = new Mycompare();
// Collections.sort(list, comparator);
Comparator comparator2 = new Mycompare2();
Collections.sort(list, comparator2);
for (Person p : list) {
System.out.println(p.getName() + " " + p.getAge());
}
}
}
/**
*
按照年龄大小排序
*
*/
class Mycompare implements Comparator<Person> {
@Override
public int compare(Person o1, Person o2) {
int age1 = o1.getAge();
int age2 = o2.getAge();
if (age1 > age2) {
return 1;
} else if (age1 == age2) {
return 0;
} else {
return -1;
}
}
}
/**
*
按名字英文顺序排序
*
*/
class Mycompare2 implements Comparator<Person> {
@Override
public int compare(Person o1, Person o2) {
String str1 = o1.getName();
String str2 = o2.getName();
int len1 = str1.length();
int len2 = str2.length();
int len = len1 >= len2 ? len2 : len1;
int flag = 0;
for (int i = 0; i < len; i++) {
if (str1.charAt(i) - str2.charAt(i) < 0) {
flag = -1;
break;
} else if (str1.charAt(i) - str2.charAt(i) == 0) {
if (i == len - 1 && len1 < len2) {
flag = -1;
break;
}
continue;
} else {
flag = 1;
break;
}
}
return flag;
}
}
class Person {
String name;
int age;
public Person(String name, int age) {
this.name = name;
this.age = age;
}
public String getName() {
return name;
}
public int getAge() {
return age;
}
}
输出结果如下
1,按英文顺序排序
a 29
absort 17
abstract 37
account 21
act 26
action 8
adjust 31
advices 23
afraid 20
back 14
boy 15
2, 按数字大小排序
action 8
back 14
boy 15
absort 17
afraid 20
account 21
advices 23
act 26
a 29
adjust 31
abstract 37