对中文名称进行排序,不多说,上代码
- package test;
- /**
- * @Title: Person.java
- * @Copyright: Copyright (c) 2012-11-19
- * @Author : zhangzhao
- * @Version 0.1
- */
- public class Person{
- private int id;
- private String name;
- 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;
- }
- }
- package test;
- import java.text.Collator;
- import java.util.Comparator;
- /**
- * @Title: SortChineseName.java
- * @Description: 中文字符排序
- * @Function: 中文字符排序
- * @Copyright: Copyright (c) 2012-11-19
- * @Author : zhangzhao
- * @Version 0.1
- */
- public class SortChineseName implements Comparator<Person>{
- Collator cmp = Collator.getInstance(java.util.Locale.CHINA);
- @Override
- public int compare(Person o1, Person o2) {
- if (cmp.compare(o1.getName(), o2.getName())>0){
- return 1;
- }else if (cmp.compare(o1.getName(), o2.getName())<0){
- return -1;
- }
- return 0;
- }
- }
- package test;
- import java.util.ArrayList;
- import java.util.Collections;
- import java.util.List;
- public class TestBean {
- public static void main(String args[]){
- List<Person> list = new ArrayList<Person>();
- Person p = new Person();
- p.setId(1);
- p.setName("张三");
- list.add(p);
- p = new Person();
- p.setId(2);
- p.setName("李四");
- list.add(p);
- p = new Person();
- p.setId(3);
- p.setName("王五");
- list.add(p);
- p = new Person();
- p.setId(4);
- p.setName("赵六");
- list.add(p);
- //正序
- Collections.sort(list, new SortChineseName());
- System.out.println("中文名称正序排列:");
- for (Person pp:list){
- System.out.println(pp.getId()+","+pp.getName());
- }
- System.out.println("---------------神奇的分割线--------------------");
- //倒序
- Collections.reverse(list);
- System.out.println("中文名称倒序排列:");
- for (Person pp:list){
- System.out.println(pp.getId()+","+pp.getName());
- }
- System.out.println("---------------神奇的分割线--------------------");
- Collections.sort(list,Collections.reverseOrder(new SortChineseName()));
- System.out.println("中文名称倒序排列:");
- for (Person pp:list){
- System.out.println(pp.getId()+","+pp.getName());
- }
- }
- }
打印结果:
中文名称正序排列:
2,李四
3,王五
1,张三
4,赵六
---------------神奇的分割线--------------------
中文名称倒序排列:
4,赵六
1,张三
3,王五
2,李四
---------------神奇的分割线--------------------
中文名称倒序排列:
4,赵六
1,张三
3,王五
2,李四