1. String array 排序:
String[] realList = ...
// sort by alphabet
AlphabetCompare ac = new AlphabetCompare();
Arrays.sort(realList, ac);
public class AlphabetCompare implements Comparator<String>{
@Override
public int compare(String str1, String str2) {
return str1.compareTo(str2);
}
}
非常简单!!
2. 为了把获取的人名按照拼音顺排序,写了下面这个类
- public class AlphabetComparator implements Comparator<String> {
- private RuleBasedCollator collator;
- public AlphabetComparator() {
- collator = (RuleBasedCollator) Collator
- .getInstance(java.util.Locale.CHINA);
- }
- @Override
- public int compare(String obj1, String obj2) {
- CollationKey c1 = collator.getCollationKey(obj1);
- CollationKey c2 = collator.getCollationKey(obj2);
- return collator.compare(((CollationKey) c1).getSourceString(),
- ((CollationKey) c2).getSourceString());
- }
- }
这个是升序,把c1和c2换一下就是降序了。
调用方法
- AlphabetComparator cfc = new AlphabetComparator();
- Collections.sort([需要排序的数据], cfc)