java下 对象中文名字排序

再一个对象数组中,对象拥有多个属性,其中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;
	}

 

转载于:https://my.oschina.net/wtzheng/blog/818753

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值