有时候我们需要多列表中的数据进行特定的排序,最近项目中用到的是按名称排序,所以简单来说一下:
效果图:
排序方法:
Collections.sort(students, new SortChineseName()); for (Student s : students) { Log.e("David", "名称正序排列:" + s.getName()); } Log.d("David", "---------------------------------------"); Collections.reverse(students); for (Student s : students) { Log.e("David", "名称倒序排列(一):" + s.getName()); } Log.d("David", "---------------------------------------"); Collections.sort(students, Collections.reverseOrder(new SortChineseName())); for (Student s : students) { Log.e("David", "名称倒序排列(二):" + s.getName()); }
sort方法
class SortChineseName implements Comparator{ /** * create by Davide * 参数说明: * ResolveInfo 为你的List集合中的类-我这里为 android系统中apk信息类 */ private Context mContext; //构造-传进来context对象 public SortChineseName(Context mContext) { this.mContext = mContext; } Collator cmp = Collator.getInstance(java.util.Locale.CHINA); @Override public int compare(ResolveInfo info1, ResolveInfo info2) { String apkName1 = info1.loadLabel(mContext.getPackageManager()).toString(); String apkName2 = info2.loadLabel(mContext.getPackageManager()).toString(); /** *create by Davide *开始比较-我这儿按照apk的名称排序,便获取apkName */ if (cmp.compare(apkName1, apkName2) > 0) { return 1; } else if (cmp.compare(apkName1, apkName2) < 0) { return -1; } return 0; } }