java、android拼音,中文姓名排序

http://blog.sina.com.cn/s/blog_81a9aa7e0100tizj.html

在java或者是android编程的时候,我们经常要用到对姓名或者其他字符串排序,现在我写写自己曾经做过的列子。
普通的数组字符串排序,通过构造器来实现:
假如在main方法中有String name[5] = {"one","张三","李四","王五","two"};
只要调用Arrays.sort(name,0,5,new Comparents());就可以了。

 
import java.text.Collator;
    import java.util.Comparator;
    import java.util.Locale;
public class Comparents implements  Comparator<Object> {
  @Override
      public int compare(Object arg0, Object arg1) {
           String one = (String)arg0;
           String two = (String)arg1;
           Collator ca = Collator.getInstance(Locale.CHINA);
           int flags = 0;
           if (ca.compare(one,two) < 0) {
         flags = -1;
           }
          else if(ca.compare(one,two) > 0) {
             flags = 1;
           }
          else {
            flags = 0;
           }
          return flags;
     }
}

 

在android中,我们经常要用到HashMap,经常用list存放HashMap,我们对List中的元素进行排序的时候,就要用到构造器了,下面具体用列子说说:

假如在main方法中有:

       public List<HashMap<String, Object>> listitem;

       listitem.add(new HashMap("name","one"));

       listitem.add(new HashMap("name","张三"));

       listitem.add(new HashMap("name","李四"));

       listitem.add(new HashMap("name","王五"));

       listitem.add(new HashMap("name","two"));

      

       Comparent comparent = new Comparent();
       Collections.sort(listitem, comparent);

 

其中在Comparent.java文件中定义方法如下:

import java.text.Collator;
import java.util.Comparator;
import java.util.HashMap;
import java.util.Locale;

public class Comparent implements  Comparator<Object> {

 @SuppressWarnings("unchecked")
 @Override
 public int compare(Object arg0, Object arg1) {
  HashMap<String, Object> name1 = (HashMap<String, Object>)arg0;
  HashMap<String, Object> name2 = (HashMap<String, Object>)arg1;
  Collator ca = Collator.getInstance(Locale.CHINA);
  int flags = 0;
  if (ca.compare((String) name1.get("name"), (String)name2.get("name")) < 0) {
   flags = -1;
  }
  else if(ca.compare((String) name1.get("name"), (String)name2.get("name")) > 0) {
   flags = 1;
  }
  else {
   flags = 0;
  }
  return flags;
 }
}

 

posted @ 2015-11-24 18:20  tc310  阅读(2860)  评论(0编辑  收藏  举报