JAVA POJO集合按照字符串字段中文拼音首字母排序

POJO: 

class ClassCodeDto {
		private String classcode8;
		private String className;

		public ClassCodeDto(String classcode8, String className) {
			super();
			this.classcode8 = classcode8;
			this.className = className;
		}

		public String getClassName() {
			return className;
		}

		public void setClassName(String className) {
			this.className = className;
		}

		public String getClasscode8() {
			return classcode8;
		}

		public void setClasscode8(String classcode8) {
			this.classcode8 = classcode8;
		}

		@Override
		public String toString() {
			return "{" + this.classcode8 + "," + this.className + "}";
		}

	}

测试代码:

public static void main(String[] args) {

		ClassCodeDto cat1 = new ClassCodeDto("234", "个人");
		ClassCodeDto cat2 = new ClassCodeDto("523", "附加");
		ClassCodeDto cat3 = new ClassCodeDto("rqw3", "安安");
		ClassCodeDto cat4 = new ClassCodeDto("34q", "江苏");
		ClassCodeDto cat5 = new ClassCodeDto("tq4", "新疆");
		ClassCodeDto cat6 = new ClassCodeDto("rq34", "北京");
		ClassCodeDto cat7 = new ClassCodeDto("wtq34", "安庆");

		// 按拼音排序
		List names = Arrays.asList(cat1, cat2, cat3, cat4, cat5, cat6, cat7);
		Collator com = Collator.getInstance(java.util.Locale.CHINA);
		Collections.sort(names, new Comparator() {

			@Override
			public int compare(ClassCodeDto o1, ClassCodeDto o2) {
				// return com.compare(o1.getClassName(), o2.getClassName());
				return com.getCollationKey(o1.getClassName()).compareTo(com.getCollationKey(o2.getClassName()));
			}
		});
		System.out.println(names);

	}

jdk版本:1.8

测试结果:

[{rqw3,安安}, {wtq34,安庆}, {rq34,北京}, {523,附加}, {234,个人}, {34q,江苏}, {tq4,新疆}]

注:

1、使用jdk1.8时,比较公式二者都会生成理想的排序效果

return com.compare(o1.getClassName(), o2.getClassName());
return com.getCollationKey(o1.getClassName()).compareTo(com.getCollationKey(o2.getClassName()));

但是当使用jdk1.6时,compare不会排序,集合顺序不变,使用getCollationKey来比较才会生效。

2、Collator源码中描述到,只比较一次时,compare拥有更好的性能,多字符串比较时,getCollationKey的效率更高。

你可能感兴趣的:(JAVA)