汉字排序之前:
peopleList.add(new NameBean("风四娘"));
peopleList.add(new NameBean("连城璧"));
peopleList.add(new NameBean("萧十一郎 "));
peopleList.add(new NameBean("沈璧君"));
peopleList.add(new NameBean("逍遥侯"));
peopleList.add(new NameBean("杨开泰"));
peopleList.add(new NameBean("沈飞云"));
peopleList.add(new NameBean("小公子"));
汉字排序之后:
PeopleList: 0==风四娘
PeopleList: 1==连城璧
PeopleList: 2==沈璧君
PeopleList: 3==沈飞云
PeopleList: 4==小公子
PeopleList: 5==萧十一
PeopleList: 6==逍遥侯
PeopleList: 7==杨开泰
特性:
1 可以自定义多音字词典,避免”重庆”变成”ZHONGQING”
2 灵活易懂,读者可以根据需要自行修改排序规则
在使用这个Util之前Android请加上这句话:
compile ‘com.github.promeg:tinypinyin:2.0.3’
public class NameBean{
public String nameChinese;//汉字: 梁超杰
public String firstLetter;//首字母: L
public String namePinYin;//拼音: LIANGCHAOJIE
public NameBean(String name) {
this.nameChinese = name;
this.namePinYin = Pinyin.toPinyin(name, "");
firstLetter = namePinYin.substring(0,1);
}
}
package com.dream;
import java.util.List;
/**
* @Description: 对汉字进行排序
* @Author: Liangchaojie
* @Create On 2018/2/26 12:51
*/
public class ChineseSortUtil {
public static void sortList(List list){
transferList(list);
}
/**
* 进行冒泡排序
* @param list
*/
private static void transferList(List list) {
for (int i=0;i1;i++){
for (int j = 0; j < list.size() -1- i; j++) {
exchangeNameOrder(j,list);
}
}
}
/**
* 交换两个名字的顺序,根据首字母判断
* @param j
* @param list
*/
private static void exchangeNameOrder(int j, List list) {
String namePinYin1 = list.get(j).namePinYin;
String namePinYin2 = list.get(j+1).namePinYin;
int size = namePinYin1.length() >= namePinYin2.length() ? namePinYin2.length() : namePinYin1.length();
for (int i=0;ichar jc = namePinYin1.charAt(i);
char jcNext = namePinYin2.charAt(i);
if(jc//A在B之前就不用比较了
break;
}
if(jc>jcNext){//A在B之后就直接交换,让A在前面B在后面
NameBean nameBean=list.get(j);
list.set(j , list.get(j+1));
list.set(j + 1, nameBean);
break;
}
//如果AB一样就继续比较后面的字母
}
}
}
使用举例:
/**
* 对联系人进行排序
*/
public class MainActivity extends AppCompatActivity {
private List peopleList;//联系人列表
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initPeopleList();
ChineseSortUtil.sortList(peopleList);
showPeopleList(peopleList);
}
private void showPeopleList(List list) {
for (int i=0;i"TAG", "PeopleList: "+i+"=="+list.get(i).nameChinese);
}
}
private void initPeopleList() {
peopleList = new ArrayList<>();
peopleList.add(new NameBean("风四娘"));
peopleList.add(new NameBean("连城璧"));
peopleList.add(new NameBean("萧十一郎 "));
peopleList.add(new NameBean("沈璧君"));
peopleList.add(new NameBean("逍遥侯"));
peopleList.add(new NameBean("杨开泰"));
peopleList.add(new NameBean("沈飞云"));
peopleList.add(new NameBean("小公子"));
}
}