需求:实现Java列表及XML列表的通用自动升序排序方案
解决方案:自动排序XML列表(XSLT)及Java列表
XSLT实现自动排序列表
以下XSLT无需指定列表名称或层级,会自动识别所有包含<item>子元素的列表节点,根据内容类型(数字/文本)完成升序排序,同时保留原XML结构:
<xsl:stylesheet version="2.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"> <!-- 复制所有节点,仅对包含item的列表节点做特殊处理 --> <xsl:template match="@*|node()"> <xsl:copy> <xsl:apply-templates select="@*|node()"/> </xsl:copy> </xsl:template> <!-- 匹配所有包含item子元素的列表节点 --> <xsl:template match="*[item]"> <xsl:copy> <!-- 自动判断item内容类型,选择对应排序规则 --> <xsl:choose> <!-- 检查第一个item是否为有效数字(兼容整数、小数) --> <xsl:when test="number(item[1]) = number(item[1])"> <xsl:apply-templates select="item"> <xsl:sort select="number(.)" data-type="number" order="ascending"/> </xsl:apply-templates> </xsl:when> <xsl:otherwise> <xsl:apply-templates select="item"> <xsl:sort select="." data-type="text" order="ascending"/> </xsl:apply-templates> </xsl:otherwise> </xsl:choose> </xsl:copy> </xsl:template> </xsl:stylesheet>
核心特性
- 自动识别所有层级下的列表节点(只要包含
<item>子元素) - 智能判断内容类型:数字按数值排序,文本按字符串自然顺序排序
- 完整保留原XML的结构、属性及非列表节点内容
Java实现列表自动升序排序
以下工具类可自动识别列表元素类型,完成对应规则的升序排序:
import java.util.ArrayList; import java.util.Collections; import java.util.List; public class ListSorter { @SuppressWarnings("unchecked") public static <T> void autoSort(List<T> list) { if (list == null || list.isEmpty()) { return; } Object firstElement = list.get(0); if (firstElement instanceof Number) { // 数字类型按数值升序排序 Collections.sort((List<Comparable>) list); } else if (firstElement instanceof String) { // 字符串按自然顺序升序排序 Collections.sort((List<String>) list); } else { // 自定义类型需实现Comparable接口,否则抛出异常 throw new IllegalArgumentException("不支持的元素类型: " + firstElement.getClass().getName()); } } // 示例用法 public static void main(String[] args) { // 字符串列表排序 List<String> cityList = new ArrayList<>(); cityList.add("Paris"); cityList.add("London"); cityList.add("Berlin"); cityList.add("Zurich"); autoSort(cityList); System.out.println(cityList); // 输出: [Berlin, London, Paris, Zurich] // 数字列表排序 List<Double> numList = new ArrayList<>(); numList.add(0.1); numList.add(20.0); numList.add(10.0); numList.add(0.01); autoSort(numList); System.out.println(numList); // 输出: [0.01, 0.1, 10.0, 20.0] } }
核心特性
- 自动检测列表第一个元素的类型,适配排序规则
- 支持所有数字类型(Integer、Double等)和字符串类型
- 自定义类型需实现
Comparable接口,否则会抛出明确的异常提示
内容的提问来源于stack exchange,提问作者Schlomo Dumbo
相关产品推荐
相关产品推荐

