排序器有两种: 一种是 implements comparable ,另一种是new comparator . 然后重写比较方法根据自己的需求可以指定根据那个字段进行排序(比如:id,age)。集合中treeset和treemap具有排序的功能,比较的时候会将不同的数据类型转化成相同的类型再进行比较排序。
下面的这个列子是根据中文名的音序排序的:
一、
先创建一个实体类(javaBean)
package com.hzgg.test;
public class Chilren {
private int id;
private int age;
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getName() {return name;
}
public void setName(String name) {
this.name = name;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
}
二、
写一个工具类存放排序器(comparator)
package hcb.util;
import java.text.Collator;
import java.util.Comparator;
import hcb.dto.hr.EmployeeAddressBook;
public class ComparatorUtils implements Comparator<Chilren>{
@Override
public int compare(Chilren o1, Chilren o2) {
Collator cmp = Collator.getInstance(java.util.Locale.CHINA);
if(cmp.compare(o1.getName(), o2.getName())>0){
return 1;
}else if(cmp.compare(o1.getName(), o2.getName())<0){
return -1;
}
return 0;
}
}
三、写测试类,用集合存储按照中文名的音序排序
public class Test {
List<Chilren> list = new ArrayList<Chilren>();
Chilren ch = new Chilren();
ch setId(1);
ch .setName("张三");
list.add(ch);
ch = new Chilren();
ch .setId(2);
ch .setName("李四");
list.add(ch);
ch = new Chilren();
ch .setId(3);
ch .setName("王五");
list.add(ch);
ch = new Chilren();
ch .setId(4);
ch .setName("赵六");
list.add(ch);
//正序
Collections.sort(list, new ComparatorUtils ());
System.out.println("中文名称正序排列:");
for (Chilren pp:list){
System.out.println(pp.getId()+","+pp.getName());
}
System.out.println("---------------分割线--------------------");
//倒序
Collections.reverse(list);
System.out.println("中文名称倒序排列:");
for (Chilren pp:list){
System.out.println(pp.getId()+","+pp.getName());
}
System.out.println("---------------分割线--------------------");
Collections.sort(list,Collections.reverseOrder(new Test()));
System.out.println("中文名称倒序排列:");
for (Chilren pp:list){
System.out.println(pp.getId()+","+pp.getName());
}
}
}