如果排序对象是List类型的,可以直接调用Collections.sort进行排序。
如果是set集合,可以用迭代器遍历查询排序,也可以用TreeSet自动排序
TreeSet<Integer> treeSet = new TreeSet<Integer>();
Set<Integer> aset = new Set<Integer>();
aset ://数据库查询的结果集或是自己添加元素
treeSet.addAll(aset);
这时set集合已经排好了
如果是map对象,也可以用TreeMap对象使其自动排序。
Java中对Map(HashMap,TreeMap,Hashtable等)的排序时间
首先简单说一下他们之间的区别:
HashMap: 最常用的Map,它根据键的HashCode值存储数据,根据键可以直接获取它的值,具有很快的访问速度。HashMap最多只允许一条记录的键为Null(多条会覆盖);允许多条记录的值为Null。非同步的。
TreeMap: 能够把它保存的记录根据键(key)排序,默认是按升序排序,也可以指定排序的比较器,当用Iterator遍历TreeMap时,得到的记录是排过序的。TreeMap不允许key的值为null。非同步的。
Hashtable: 与HashMap类似,不同的是:key和value的值均不允许为null;它支持线程的同步,即任一时刻只有一个线程能写Hashtable,因此也导致了Hashtale在写入时会比较慢。
LinkedHashMap:保存了记录的插入顺序,在用Iterator遍历LinkedHashMap时,先得到的记录肯定是先插入的.在遍历的时候会比HashMap慢。key和value均允许为空,非同步的。
TreeMap默认按key进行升序排序,如果想改变默认的顺序,可以使用比较器:
Map map = new TreeMap(newComparator(){
public int compare(Stringobj1,String obj2){
//降序排序
returnobj2.compareTo(obj1);
}
});
map.put("month", "Themonth");
map.put("bread", "Thebread");
map.put("attack", "Theattack");
Set keySet =map.keySet();
Iterator iter =keySet.iterator();
while(iter.hasNext()){
String key =iter.next();
System.out.println(key+":"+map.get(key));
}
如果要对TreeMap按照value的值进行排序,或者对HashMap,Hashtable,LinkedHashMap进行排序,则可以使用Map.Entry接口结合List实现:
eg.1 对TreeMap按照value值升序:
List> mappingList =null;
Map map = newTreeMap();
map.put("aaaa","month");
map.put("bbbb","bread");
map.put("ccccc","attack");
//通过ArrayList构造函数把map.entrySet()转换成list
mappingList = newArrayList>(map.entrySet());
//通过比较器实现比较排序
Collections.sort(mappingList, newComparator>(){
public int compare(Map.Entrymapping1,Map.Entry mapping2){
returnmapping1.getValue().compareTo(mapping2.getValue());
}
});
for(Map.Entrymapping:mappingList){
System.out.println(mapping.getKey()+":"+mapping.getValue());
}
eg.2对HashMap(或Hashtable,LinkedHashMap)按照key的值升序:
List> mappingList =null;
Map map = newHashMap();
map.put("month","month");
map.put("bread","bread");
map.put("attack","attack");
//通过ArrayList构造函数把map.entrySet()转换成list
mappingList = newArrayList>(map.entrySet());
//通过比较器实现比较排序
Collections.sort(mappingList, newComparator>(){
public int compare(Map.Entrymapping1,Map.Entry mapping2){
returnmapping1.getKey().compareTo(mapping2.getKey());
}
});
for(Map.Entrymapping:mappingList){
System.out.println(mapping.getKey()+":"+mapping.getValue());
}