java list按固定值排序_list集合按元素的某一属性排序

packagecom.songyan.demo.collection.list.sort;importjava.lang.reflect.InvocationTargetException;importjava.lang.reflect.Method;importjava.math.BigDecimal;importjava.util.Collections;importjava.util.Comparator;importjava.util.Date;importjava.util.List;/***@authorsongyan

* @date 2020年5月21日 下午4:33:10

* @desc 基于反射实现对一个列表的任意字段的排序*/

public classSort3 {/*** 对"指定的集合"根据"指定的字段"排序

*

*@paramlist

*@paramfield*/

public static void sort(Listlist, String field) {if (list == null || list.size() == 0) {return;

}else{final String fieldName =getFieldName(field);

Collections.sort(list,new Comparator() {

@Overridepublic intcompare(T o1, T o2) {try{

Object val1=getFieldValue(o1, fieldName);

Object val2=getFieldValue(o2, fieldName);if (val1 == null) {if (val2 == null) {return 0;

}else{return -1;

}

}if (val2 == null)return -1;if (val1 instanceof BigDecimal && val2 instanceofBigDecimal) {return -((BigDecimal) val1).compareTo((BigDecimal) val2);

}else if (val1 instanceof Integer && val2 instanceofInteger) {return -((Integer) val1).compareTo((Integer) val2);

}else if (val1 instanceof String && val2 instanceofString) {return -((String) val1).compareTo((String) val2);

}else if (val1 instanceof Date && val2 instanceofDate) {return -((Date) val1).compareTo((Date) val2);

}

}catch(Exception e) {

e.printStackTrace();

}return 1;

}

});

}

}/*** 将字段名首字母大写

*

*@paramfield

*@return

*/

private staticString getFieldName(String field) {if (field != null && field.length() > 0) {if (field.length() == 1) {

field= field.substring(0, 1).toUpperCase();

}else{

field= field.substring(0, 1).toUpperCase() + field.substring(1);

}

}returnfield;

}/*** 获取属性值

*

*@param

*@return*@throwsSecurityException

*@throwsNoSuchMethodException

*@throwsInvocationTargetException

*@throwsIllegalArgumentException

*@throwsIllegalAccessException*/

private static Object getFieldValue(T o1, String field) throwsNoSuchMethodException, SecurityException,

IllegalAccessException, IllegalArgumentException, InvocationTargetException {

Method getter1= o1.getClass().getDeclaredMethod("get" +field);returngetter1.invoke(o1);

}

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值