Reputation: 81
Im using the code below to read a csv file and would like to put result in a map
def fileName = 'C:/temp/exampleCSV.csv'
def reader = new CSVReader(new FileReader(new File(fileName)))
def header = reader.readNext()
def rows = reader.readAll().collect { row ->
(0..(row.size()-1)).collectEntries { [header[it], row[it]] }
}
CSV:
name;cuInfo;service;startDate;appId
Apple;T12;3;14-02-16 10:00;G12351
Apple;T13;3;14-01-16 13:00;G12352
Google;T14;9;10-01-16 11:20;G12301
Microsoft;T15;10;26-02-16 10:20;G12999
But the code above give me the output:
[
[name;cuInfo;service;startDate;appId:Apple;T12;3;14-02-16 10:00;G12351],
[name;cuInfo;service;startDate;appId:Apple;T13;3;14-01-16 13:00;G12352],
[name;cuInfo;service;startDate;appId:Google;T14;9;10-01-16 11:20;G12301],
[name;cuInfo;service;startDate;appId:Microsoft;T15;10;26-02-16 10:20;G12999]
]
I would like to get this structure as the map below?
[
[name:"Apple", cuInfo:"T12",service:"3",startDate:"14-01-16 13:22",appId:"G12355"],
[name:"Apple",cuInfo:"T13",service:"3",startDate:"12-02-16 13:00",appId:"G12356"],
[name:"Google",cuInfo:"T14",service:"9",startDate:"10-01-16 11:20",appId:"G12300"],
[name:"Microsoft",cuInfo:"T15",service:"10",startDate:"26-02-16 10:20",appId:"G12999"]
]
Upvotes: 2
Views: 10092
Reputation: 9885
To get the data from the CSV file into the same structure (a list of Maps) as the query output, you can do this:
def reader = new CSVReader(new FileReader(new File(fileName)))
def output = reader.collect { it[0].split(';') }.with { rows ->
def header = rows.head()
def dataRows = rows.tail()
dataRows.collect { row ->
[header, row].transpose().collectEntries()
}
}
The CSV rows are split into columns, the header and the remaining rows are gathered, and then they are transformed.
The transpose()
creates a structure like this for each data row:
[[name, Apple], [cuInfo, T12], [service, 3], [startDate, 14-02-16 10:00], [appId, G12351]]
And collectEntries()
turns this into a Map
:
[name:Apple, cuInfo:T12, service:3, startDate:14-02-16 10:00, appId:G12351]
Upvotes: 7