JAVA版List<Map>排序,按字符或数字类型排序,支持正序倒序

本文介绍了一种对 List<Map> 结构进行排序的方法,支持按字符串或数字类型的字段进行正序或倒序排列,并考虑了空字符及非数字的情况。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

List<Map>排序,按字符或数字类型排序,支持正序倒序,数字排序时处理空字符和非数字排序:空<非数字<数字
/**
 * 数字校验(正、负、小数)
 * @param s
 * @return
 */
public static boolean isNumeric(String s) {
	if (s != null && !"".equals(s.trim()))
		return s.matches("^-?\\d+(\\.\\d+)?$");
	else
		return false;
}

/**
 * List排序
 * @param resultList Map数组
 * @param orderColumn 排序列名
 * @param isString 是否按字符串排序,否则按数字排序
 * @param isAsc 是否正序
 * @throws Exception
 */
public static void listSort(List> resultList, final String orderColumn, final boolean isString,
		final boolean isAsc) throws Exception {
	// 返回的结果集
	Collections.sort(resultList, new Comparator>() {
		public int compare(Map o1, Map o2) {
			String s1 = StringUtils.getString(o1.get(orderColumn));
			String s2 = StringUtils.getString(o2.get(orderColumn));
			if (isString) {
				return s1.compareTo(s2) * (isAsc ? 1 : -1);
			} else {
				if (s1.equals(""))
					return isAsc ? -1 : 1;
				if (s2.equals(""))
					return isAsc ? 1 : -1;
				if (!isNumeric(s1) && !isNumeric(s2))
					return s1.compareTo(s2) * (isAsc ? 1 : -1);
				;
				if (!isNumeric(s1))
					return isAsc ? -1 : 1;
				if (!isNumeric(s2))
					return isAsc ? 1 : -1;
				return new BigDecimal(s1).compareTo(new BigDecimal(s2)) * (isAsc ? 1 : -1);
			}
		}
	});
}

public static void main(String[] args) throws Exception {
	List> list = new ArrayList>();

	Map map1 = new HashMap();
	Map map2 = new HashMap();
	Map map3 = new HashMap();
	Map map4 = new HashMap();
	Map map5 = new HashMap();

	map1.put("number", null);
	map2.put("number", "44a");
	map3.put("number", -3);
	map4.put("number", "36c");
	map5.put("number", 11.1234);
	list.add(map1);
	list.add(map2);
	list.add(map3);
	list.add(map4);
	list.add(map5);

	listSort(list, "number", false, false);

	System.out.println(list);
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值