一. 简单排序
package test;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
public class Test {
public static void main(String[] args) throws Exception {
//对列表排序
List list = new ArrayList();
list.add("aaa");
list.add("ccc");
list.add("bbb");
System.out.println("列表排序前");
System.out.println(list.get(0) + " " + list.get(1) + " " + list.get(2));
//对list进行字典排序
Collections.sort(list);
System.out.println("列表排序后");
System.out.println(list.get(0) + " " + list.get(1) + " " + list.get(2));
//对数组排序
String s[] = {"aaa", "ccc", "bbb"};
System.out.println("数组排序前");
System.out.println(s[0] + " " + s[1] + " " + s[2]);
Arrays.sort(s);
System.out.println("数组排序后");
System.out.println(s[0] + " " + s[1] + " " + s[2]);
}
}
二.稍微复杂点的
下面是对列表中的一个自实现hash表根据其key1字段值进行降序排列的例子排序。注意实现的关键在于被排序的对象类型实现了java.lang.Comparable接口。 看了下面的例子,相信列表中在存放其他类型,如javabean实现排序也就知道怎么做了。
package test;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
public class Test {
public static void main(String[] args) throws Exception {
//对列表排序
List list = new ArrayList();
MyMap map1 = new MyMap();
map1.put("key1", 1);
MyMap map2 = new MyMap();
map2.put("key1", 2);
list.add(map1);
list.add(map2);
System.out.println("排序前");
System.out.println(list.get(0) + " " + list.get(1));
Collections.sort(list);
System.out.println("排序后(降序排列)");
System.out.println(list.get(0) + " " + list.get(1));
}
}
class MyMap extends HashMap implements Comparable {
public MyMap(){
super();
}
/**
* 降序排列
*/
public int compareTo(Object b) {
MyMap m = (MyMap) b;
int i = Integer.parseInt(this.get("key1") + "");
int you = Integer.parseInt(m.get("key1") + "");
if(i > you)
return -1;
else if(i < you)
return 1;
else
return 0;
}
}
当然也可以用下面的方法来排序,这就是引用匿名类的技巧
package test;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
@SuppressWarnings("unchecked")
public class Test {
public static void main(String[] args) throws Exception {
//对列表排序
List list = new ArrayList();
list = new ArrayList();
Map map11 = new HashMap();
map11.put("key1", 1);
Map map12 = new HashMap();
map12.put("key1", 2);
list.add(map11);
list.add(map12);
System.out.println("排序前");
System.out.println(list.get(0) + " " + list.get(1));
Collections.sort(list, new Comparator() {
public int compare(Object a, Object b) {
Map aa = (Map) a;
Map bb = (Map) b;
int i = Integer.parseInt(aa.get("key1") + "");
int you = Integer.parseInt(bb.get("key1") + "");
if(i > you)
return -1;
else if(i < you)
return 1;
else
return 0;
}
});
System.out.println("排序后(降序排列)");
System.out.println(list.get(0) + " " + list.get(1));
}
}