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

使用Groovy读取CSV文件并转换为Map列表(无外部依赖)

Pure Groovy Solution: Read CSV to List of Maps (No External Libraries)

Got it, let's tackle this—here's a straightforward, dependency-free Groovy script that'll turn your CSV into the list of Maps you need. It’s lightweight and fits exactly your use case.

The Code

// Replace with your actual CSV file path
def csvFilePath = 'your-service-limits.csv'
def csvFile = new File(csvFilePath)

// Read all lines from the CSV
def allLines = csvFile.readLines()

// Extract the header row to use as Map keys
def headers = allLines[0].split(',').collect { it.trim() }

// Convert each data row into a Map, then collect into a list
def serviceLimits = allLines[1..-1].collect { dataLine ->
    // Split the row into individual values, trimming any accidental whitespace
    def values = dataLine.split(',').collect { it.trim() }
    // Pair headers with values and convert to a Map
    [headers, values].transpose().collectEntries()
}

// Print the result to verify
println serviceLimits

How It Works

Let’s break down what’s happening here:

  • Read the File: readLines() pulls all lines from the CSV into a list, making it easy to separate headers and data.
  • Extract Headers: The first line is split by commas to get our Map keys (like Sno, Service), and we trim each to handle any unexpected spaces.
  • Convert Rows to Maps: For each data line, we split into values, then use transpose() to pair each header with its corresponding value. collectEntries() turns that paired list into a proper Groovy Map.
  • Collect into List: All those Maps get gathered into a single list, which matches exactly the structure you’re looking for.

Example Output

When you run this with your sample CSV, you’ll get:

[
    [Sno:"1", Service:"ProposalService", Operation:"upsert", ResponseTimeLimit:"50"],
    [Sno:"2", Service:"ScheduleService", Operation:"getReservation", ResponseTimeLimit:"10"],
    [Sno:"3", Service:"ScheduleService", Operation:"bookAppointment", ResponseTimeLimit:"23"]
]

Quick Note

This works perfectly for your simple CSV format. If you ever need to handle more complex CSVs (like values with commas inside quotes), you’d need to add a bit more logic to parse those cases—but for your current requirements, this is clean and efficient.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.22 08:08:08