一,Collections.sort的简单排序
TestCollections.java
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
public class TestCollections implements Comparator<String> {
public static void main(String[] args) {
TestCollections tcl = new TestCollections();
List<String> list = getList();
tcl.test(list);
for(String temp : list){
System.out.println(temp);
}
}
public static List<String> getList() {
List<String> list = new ArrayList<String>();
list.add("11");
list.add("32");
list.add("31");
list.add("41");
list.add("15");
return list;
}
public void test(List<String> list){
Collections.sort(list, new TestCollections());
}
@Override
public int compare(String o1, String o2) {
return -o1.compareTo(o2);
}
}
输出结果
41
32
31
15
11
二,Comparable排序
实体类Person需要implements Comparable接口,然后重写compareTo方法
public class Person implements Comparable<Person> {
public String name;
public int age;
public Person(String name, int age) {
this.name = name;
this.age = age;
}
public int compareTo(Person another) {
int i = name.compareTo(another.name); //比较名字字符串
if (i == 0) { //如果名字一样,则继续比较年龄
return age - another.age;
} else { //首先比较名字,名字不一样,则返回比较结果
return i;
}
}
}
private void sortByComparable() {
Person p1 = new Person("bbb", 20);
Person p2 = new Person("aaa", 18);
Person p3 = new Person("bbb", 16);
List<Person> list = new ArrayList<Person>();
list.add(p1);
list.add(p2);
list.add(p3);
//排序
Collections.sort(list);
//输出
Log.d(TAG, "-----------使用Comparable实现的排序-----------");
for(Person item : list) {
Log.d(TAG, "name = "+item.name+", age = "+item.age);
}
}
输出结果:
———–使用Comparable实现的排序———–
name = aaa, age = 18
name = bbb, age = 16
name = bbb, age = 20
三,Comparator实现排序
public class Person {
public String name;
public int age;
public Person(String name, int age) {
this.name = name;
this.age = age;
}
}
比较器MyComparator的实现,主要是覆盖compare方法
public class MyComparator implements Comparator<Person> {
public int compare(Person one, Person two) {
int i = one.name.compareTo(two.name); //比较名字字符串
if (i == 0) { //如果名字一样,则继续比较年龄
return one.age - two.age;
} else { //首先比较名字,名字不一样,则返回比较结果
return i;
}
}
}
private void sortByComparator() {
Person p1 = new Person("bbb", 20);
Person p2 = new Person("aaa", 18);
Person p3 = new Person("bbb", 16);
List<Person> list = new ArrayList<Person>();
list.add(p1);
list.add(p2);
list.add(p3);
//排序
Collections.sort(list, new MyComparator());
//输出
Log.d(TAG, "-----------使用Comparator实现的排序-----------");
for(Person item : list) {
Log.d(TAG, "name = "+item.name+", age = "+item.age);
}
}
输出结果:
———–使用Comparator实现的排序———–
name = aaa, age = 18
name = bbb, age = 16
name = bbb, age = 20