I am using Groovy to read from a CSV file which has the below fields:
Code Name Class
--- ----- ----
1701 Enterprise Constitution
1864 Reliant Miranda
What is the best way to represent this data in Groovy?
I was thinking a HashMap
where Code is the key and the value is a POGO with two fields ( Name and Class ). But is there a groovier way?
Using a plain Map
with code
as a key is ok enough. It depends on what you need to do exactly. If you need to transform this data into Map
that's the way to go.
However groovy is so elastic in data processing that you can also create a POGO and transform this CSV data into a list. It can be easily grouped by code
or whatever you need.
Also, maybe creating a POGO isn't necessary? In such case use code
aa key to.. Map
.
With a POGO and the TupleConstructor
AST transformation, parsing CSV into a list is usually quite straightforward:
@Grapes(
@Grab(group='org.apache.commons', module='commons-csv', version='1.2')
)
import groovy.transform.*
import org.apache.commons.csv.*
@ToString
@TupleConstructor
class Test {
int code
String name
String type
}
def text = ''' Code,Name,Class
1701,Enterprise,Constitution
1864,Reliant,Miranda'''
def parsed = CSVParser.parse(text, CSVFormat.EXCEL.withHeader().withIgnoreSurroundingSpaces().withQuote(null))
def result = parsed.getRecords().collect { new Test(it.Code as int, it.Name, it['Class']) }
assert '[Test(1701, Enterprise, Constitution), Test(1864, Reliant, Miranda)]' == result.toString()
assert 'Enterprise' == result.find({ it.code == 1701 }).name
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.