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

如何用Java 8 Stream一行代码转换List<String[]>中的日期格式?

用Java 8 Stream转换日期格式的解决方案

嘿,当然可以用Java 8的Stream API搞定这个需求!而且完全能以流式风格完成日期格式从dd/MM/yyyy到yyyy/MM/dd的转换,同时保留数组里的其他元素不变。

关键注意点先提一句

这里要纠正一个小细节:你写的dd/mm/yyyy里的小写mm代表的是分钟,月份必须用大写MM才能正确解析,不然会报错哦!

完整实现代码

先导入必要的类:

import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

然后是核心处理逻辑:

public class DateConverter {
    public static void main(String[] args) {
        // 初始化你的原始数据
        List<String[]> dateList = new ArrayList<>();
        String[] a = {"12/2/2018", "a1", "a2"};
        String[] b = {"13/3/2018", "b1", "b2"};
        String[] c = {"14/4/2018", "c1", "c2"};
        dateList.add(a);
        dateList.add(b);
        dateList.add(c);

        // 定义输入输出的日期格式化器
        DateTimeFormatter inputFormatter = DateTimeFormatter.ofPattern("dd/MM/yyyy");
        DateTimeFormatter outputFormatter = DateTimeFormatter.ofPattern("yyyy/MM/dd");

        // 一行流式处理(逻辑上的一行,拆分是为了可读性)
        List<String[]> convertedDates = dateList.stream()
                .map(arr -> new String[]{
                        LocalDate.parse(arr[0], inputFormatter).format(outputFormatter),
                        arr[1],
                        arr[2]
                })
                .collect(Collectors.toList());

        // 打印验证结果
        convertedDates.forEach(arr -> System.out.println("{" + String.join(", ", arr) + "}"));
    }
}

更灵活的适配写法(支持任意长度数组)

如果你的数组长度不固定,不想硬编码下标,可以用数组复制的方式,适用性更强:

import java.util.Arrays;

// ... 其他代码不变

List<String[]> convertedDates = dateList.stream()
        .map(arr -> {
            String[] newArr = Arrays.copyOf(arr, arr.length);
            newArr[0] = LocalDate.parse(arr[0], inputFormatter).format(outputFormatter);
            return newArr;
        })
        .collect(Collectors.toList());

异常处理小提示

如果原始数据里可能存在格式错误的日期,可以加个异常捕获,避免整个流处理崩溃:

.map(arr -> {
    String convertedDate;
    try {
        convertedDate = LocalDate.parse(arr[0], inputFormatter).format(outputFormatter);
    } catch (Exception e) {
        // 这里可以按需求处理,比如保留原字符串或标记错误
        convertedDate = arr[0];
        System.err.println("日期格式错误:" + arr[0]);
    }
    String[] newArr = Arrays.copyOf(arr, arr.length);
    newArr[0] = convertedDate;
    return newArr;
})

运行代码后,就能得到你期望的输出:

{"2018/02/12", "a1", "a2"}
{"2018/03/13", "b1", "b2"}
{"2018/04/14", "c1", "c2"}

(如果想要月份显示为一位数,比如2018/2/12,把输出格式改成yyyy/M/dd就行)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.14 06:35:43