java基本排序

在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;
 }
}


你可能感兴趣的:(java基本排序)