@@ -36,46 +36,55 @@ class CsvWriter {
36
36
}
37
37
38
38
void apply (List records , Path path ) {
39
- Collection columns
40
- if ( header == true ) {
41
- final first = records. first()
42
- if ( first ! instanceof Map )
43
- throw new IllegalArgumentException (' Records must be map objects when header=true' )
44
- columns = ((Map )first). keySet()
45
- }
46
- else if ( header instanceof List ) {
47
- columns = header
48
- }
49
- else {
50
- columns = null
51
- }
52
-
53
39
path. delete()
54
40
41
+ final columns = columnHeaders(header, records)
55
42
if ( columns )
56
43
path << columns. collect(column -> " \" ${ column} \" " ). join(sep) << ' \n '
57
44
58
- for ( final record : records ) {
59
- Collection values
60
- if ( record instanceof List ) {
61
- values = record
62
- }
63
- else if ( record instanceof Map ) {
64
- values = columns
65
- ? record. subMap(columns). values()
66
- : record. values()
67
- }
68
- else if ( isSerializable(record) ) {
69
- values = [ record ]
70
- }
71
- else {
72
- throw new IllegalArgumentException (" Record of type `${ record.class.name} ` can not be serialized to CSV" )
73
- }
45
+ if ( records. isEmpty() )
46
+ path << ' '
74
47
48
+ for ( final record : records ) {
49
+ final values = rowValues(record, columns)
75
50
path << values. collect(v -> " \" ${ toCsvString(v)} \" " ). join(sep) << ' \n '
76
51
}
77
52
}
78
53
54
+ private static Collection columnHeaders (Object header , List records ) {
55
+ if ( header instanceof List ) {
56
+ return header
57
+ }
58
+
59
+ if ( header == true && ! records. isEmpty() ) {
60
+ final first = records. first()
61
+ if ( first instanceof Map )
62
+ return first. keySet()
63
+ else
64
+ throw new IllegalArgumentException (' Records must be map objects when header=true' )
65
+ }
66
+
67
+ return null
68
+ }
69
+
70
+ private static Collection rowValues (Object record , Collection columns ) {
71
+ if ( record instanceof List ) {
72
+ return record
73
+ }
74
+
75
+ if ( record instanceof Map ) {
76
+ return columns
77
+ ? record. subMap(columns). values()
78
+ : record. values()
79
+ }
80
+
81
+ if ( isSerializable(record) ) {
82
+ return [ record ]
83
+ }
84
+
85
+ throw new IllegalArgumentException (" Record of type `${ record.class.name} ` can not be serialized to CSV" )
86
+ }
87
+
79
88
private static boolean isSerializable (value ) {
80
89
return value == null
81
90
|| value instanceof Boolean
0 commit comments