java中文排序
import java.text.CollationKey;
import java.text.Collator;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import com.google.common.collect.Lists;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.ToString;
import org.apache.commons.collections.CollectionUtils;
import org.junit.Test;
/**
* @author sq
* @Date 2019-10-10
*/
public class ChinaSortTest {
@Test
public void test() {
UserInfo userInfo0 = UserInfo.builder().name("张三").age(11).build();
UserInfo userInfo1 = UserInfo.builder().name("李四").age(12).build();
UserInfo userInfo2 = UserInfo.builder().name("王五").age(13).build();
UserInfo userInfo3 = UserInfo.builder().name("张哈哈").age(11).build();
UserInfo userInfo4 = UserInfo.builder().name("李哈哈").age(11).build();
UserInfo userInfo5 = UserInfo.builder().name("小强").age(11).build();
List<UserInfo> userList = Lists.newArrayList(
userInfo0,
userInfo1,
userInfo2,
userInfo3,
userInfo4,
userInfo5);
sortDistrictInfo(userList);
System.out.println(userList);
}
/**
* 排序
* @param userInfos
*/
private void sortDistrictInfo(List<UserInfo> userInfos) {
if (CollectionUtils.isNotEmpty(userInfos)) {
Collections.sort(userInfos, nameChina);
}
}
/**
* 中文比较器
*/
private static Comparator<UserInfo> nameChina = new Comparator<UserInfo>() {
Collator cmp = Collator.getInstance(java.util.Locale.CHINA);
@Override
public int compare(UserInfo d1, UserInfo d2) {
String d1Name = d1.getName() == null ? "" : d1.getName();
String d2Name = d2.getName() == null ? "" : d2.getName();
CollationKey c1 = cmp.getCollationKey(d1Name);
CollationKey c2 = cmp.getCollationKey(d2Name);
return cmp.compare(c1.getSourceString(), c2.getSourceString());
}
};
}
@Data
@Builder
@AllArgsConstructor
@NoArgsConstructor
@ToString
class UserInfo {
private String name;
private Integer age;
}
结果:
[UserInfo(name=李哈哈, age=11), UserInfo(name=李四, age=12), UserInfo(name=王五, age=13), UserInfo(name=小强, age=11), UserInfo(name=张哈哈, age=11), UserInfo(name=张三, age=11)]