1、首先自定义一个Comparator:
public class SortStrUtil implements Comparator<String> {
//这个类是处理中文排序的关键
private Collator collator=Collator.getInstance();
@Override
public int compare(String s1, String s2) {
CollationKey key1 = collator.getCollationKey(s1);
CollationKey key2 = collator.getCollationKey(s2);
return key1.compareTo(key2);
}
}
2、创建一个Student类:
public class Student implements Serializable{
private int id;
private String name;
private int age;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
@Override
public String toString() {
return "Student [id=" + id + ", name=" + name + ", age=" + age + "]";
}
public Student(int id, String name, int age) {
super();
this.id = id;
this.name = name;
this.age = age;
}
public Student() {
super();
// TODO Auto-generated constructor stub
}
3、测试类:
public class TestStudent {
@Test
public void testStudent() {
Student s1=new Student(1,"中国",21);
Student s2=new Student(1,"美国",21);
Student s3=new Student(1,"英国",21);
TreeMap<String, Student> tm=new TreeMap<>(new SortStrUtil());
tm.put(s1.getName(), s1);
tm.put(s2.getName(), s2);
tm.put(s3.getName(), s3);
Set<String> keySet = tm.keySet();
Iterator<String> iterator = keySet.iterator();
while(iterator.hasNext()) {
Student student = tm.get(iterator.next());
System.out.println(student);
}
}
}
测试结果,中文根据拼音排序了:
Student [id=1, name=美国, age=21]
Student [id=1, name=英国, age=21]
Student [id=1, name=中国, age=21]