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

如何将marathon文件的time字段存入TreeMap?附现有Java代码

解决你的marathon文件处理与TreeMap存储问题

看起来你已经迈出了第一步,不过当前代码输出的是第一个字段(sex),而你需要的是第二个字段(time),同时还要把它存入TreeMap。我来帮你一步步调整代码:

1. 先修正time字段的输出

你的代码里System.out.println(ar[0]);是取第一个元素,要获取time字段应该用ar[1],另外注意示例数据里逗号后面有空格,所以需要用trim()去掉前后多余的空格,避免输出带空格的时间字符串:

String[] ar = str.split(",");
if (ar.length >= 2) { // 防止格式错误的行导致数组越界
    String time = ar[1].trim();
    System.out.println(time);
}

2. 引入TreeMap存储time字段

TreeMap是键值对结构,你需要明确用什么作为键,什么作为值:

  • 如果想按时间排序存储,且时间唯一,可以用LocalTime(时间对象)作为键,运动员信息作为值(这样TreeMap会自动按时间顺序排序)
  • 如果时间可能重复,建议用运动员姓名(或其他唯一标识)作为键,时间作为值,避免覆盖数据

下面是完整的优化代码,我用了try-with-resources(自动关闭流,更安全),同时加入了TreeMap存储,还处理了时间格式转换:

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.time.LocalTime;
import java.time.format.DateTimeFormatter;
import java.util.Map;
import java.util.TreeMap;

public class Text {
    public static void main(String[] args) {
        // 定义时间格式,匹配你的数据格式:时:分:秒.毫秒
        DateTimeFormatter timeFormatter = DateTimeFormatter.ofPattern("H:mm:ss.S");
        // 用LocalTime作为键,运动员姓名作为值,自动按时间排序
        TreeMap<LocalTime, String> timeAthleteMap = new TreeMap<>();

        try (BufferedReader in = new BufferedReader(new FileReader("marathon"))) {
            // 跳过第一行的标题行(sex、time这些字段名)
            in.readLine();
            
            String str;
            while ((str = in.readLine()) != null) {
                String[] ar = str.split(",");
                // 确保行数据至少有3个字段,避免格式错误
                if (ar.length >= 3) {
                    String timeStr = ar[1].trim();
                    String athlete = ar[2].trim();
                    
                    // 输出time字段
                    System.out.println(timeStr);
                    
                    // 把字符串时间转换为LocalTime对象,存入TreeMap
                    try {
                        LocalTime time = LocalTime.parse(timeStr, timeFormatter);
                        timeAthleteMap.put(time, athlete);
                    } catch (Exception e) {
                        System.out.println("时间格式错误:" + timeStr);
                    }
                }
            }

            // 遍历TreeMap,查看存储的内容(自动按时间排序)
            System.out.println("\nTreeMap中存储的时间与运动员对应关系:");
            for (Map.Entry<LocalTime, String> entry : timeAthleteMap.entrySet()) {
                System.out.println(entry.getKey() + " -> " + entry.getValue());
            }

        } catch (IOException e) {
            System.out.println("文件读取错误:" + e.getMessage());
        }
    }
}

关键细节说明

  • try-with-resources:不用手动调用in.close(),JVM会自动处理流的关闭,避免资源泄漏
  • 时间转换:用LocalTime代替字符串存储时间,不仅能让TreeMap按实际时间顺序排序,还能方便后续的时间计算和比较
  • 异常处理:增加了时间格式解析的异常捕获,避免某一行格式错误导致整个程序崩溃
  • 数组越界检查:判断ar.length >= 3,确保能获取到time和athlete字段,避免格式错误的行抛出异常

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.19 03:22:43