You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Java如何用split、replace方法将10x2021格式字符串转为2021-10格式

修正后的实现代码

public static List<String> foo(List<HistoryItem> historyItems) {
    // 修复原代码逻辑漏洞:原过滤生成的collect集合未被使用,循环遍历了全量入参导致过滤规则失效
    List<HistoryItem> filteredItems = historyItems.stream()
            .filter(item -> item.getCreditStatus().equals(Long.valueOf("009")) || item.getCreditStatus().equals(Long.valueOf("0010")))
            .collect(Collectors.toList());
    List<String> reportingPeriods = new ArrayList<>();
    for (HistoryItem historyItem : filteredItems) {
        String originalPeriod = historyItem.getReportingPeriod();
        // 以x为分隔符拆分原始字符串,拆分后第一位是月份、第二位是年份
        String[] parts = originalPeriod.split("x");
        // 格式校验避免数组越界,按「年份-月份」拼接得到目标格式
        if (parts.length == 2) {
            String convertedPeriod = parts[1] + "-" + parts[0];
            reportingPeriods.add(convertedPeriod);
        }
        // 可根据业务需求补充非法格式的兜底逻辑,比如保留原字符串/抛出异常
    }
    return reportingPeriods;
}

可选Stream简化写法

public static List<String> foo(List<HistoryItem> historyItems) {
    return historyItems.stream()
            .filter(item -> item.getCreditStatus().equals(Long.valueOf("009")) || item.getCreditStatus().equals(Long.valueOf("0010")))
            .map(HistoryItem::getReportingPeriod)
            .map(original -> {
                String[] parts = original.split("x");
                return parts.length == 2 ? parts[1] + "-" + parts[0] : original;
            })
            .collect(Collectors.toList());
}

以上代码的核心转换逻辑是通过split("x")把10x2021这类原始字符串拆分为月份和年份两部分,调换顺序后用-拼接即可得到你需要的2021-10格式,完全适配你给出的2021-10、2021-9输出要求。

内容的提问来源于stack exchange,提问作者iwritecomeinmymind

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.26 16:06:08