java下 对象中文名字排序

原创
2017/01/04 19:33
阅读数 470

再一个对象数组中,对象拥有多个属性,其中name属性可能有中文名,实现该数组的排序代码如下:

/**
*  @author z.wantong
**/
public List<?> sort(List<?> originList , final String referAttribute , final boolean isAsc){
		if(referAttribute == null || "".equals(referAttribute.trim())) return originList;
		
		Collections.sort(originList, new Comparator<Object>(){

			//中文排序
			Collator cmp = Collator.getInstance(java.util.Locale.CHINA);
			@Override
			public int compare(Object o1, Object o2) {
				int ret = 0;
				try {
					Class tartgetClass = o1.getClass();
					Field field = tartgetClass.getDeclaredField(referAttribute);
					field.setAccessible(true);
					Object o1Value = field.get(o1); 
					Object o2Value = field.get(o2); 
					CollationKey c1 = cmp.getCollationKey(o1Value.toString());
					CollationKey c2 = cmp.getCollationKey(o2Value.toString());
					if(isAsc)
						ret = cmp.compare(c1.getSourceString(), c2.getSourceString()); 
					else
						ret = cmp.compare(c2.getSourceString(), c1.getSourceString()); 
				} catch (NoSuchFieldException | SecurityException e) {
					e.printStackTrace();
				} catch (IllegalArgumentException e) {
					e.printStackTrace();
				} catch (IllegalAccessException e) {
					e.printStackTrace();
				}
				return ret;
			}
			
		});
		return originList;
	}

 

展开阅读全文
打赏
0
1 收藏
分享
加载中
更多评论
打赏
0 评论
1 收藏
0
分享
返回顶部
顶部