-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathPivotableCSVReader.java
89 lines (70 loc) · 2.25 KB
/
PivotableCSVReader.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
package test.streams;
import java.io.Closeable;
import java.io.Reader;
import java.io.IOException;
import java.util.Map;
import java.util.Iterator;
import java.util.Optional;
import org.apache.commons.csv.CSVParser;
import org.apache.commons.csv.CSVFormat;
import org.apache.commons.csv.CSVRecord;
public class PivotableCSVReader implements Closeable, Iterable<RowGroup> {
private final Reader wrapped;
private final CSVParser parser;
private final String[] pivotColumns;
public PivotableCSVReader(Reader wrapped, String[] pivotColumns, CSVFormat format) throws IOException {
this.wrapped = wrapped;
this.pivotColumns = pivotColumns;
parser = new CSVParser(wrapped, format);
}
@Override
public void close() throws IOException {
wrapped.close();
}
@Override
public Iterator<RowGroup> iterator() {
return new PivotableCSVReaderIterator();
}
private class PivotableCSVReaderIterator implements Iterator<RowGroup> {
private final Iterator<CSVRecord> parserIterator;
private Optional<CSVRecord> pendingRow = Optional.empty();
private PivotableCSVReaderIterator(){
parserIterator = parser.iterator();
}
public RowGroup next() {
RowGroup group = pendingRow.map( row -> new RowGroup(parser.getHeaderMap(), row))
.orElse(new RowGroup(parser.getHeaderMap()));
boolean endOfGroup = false;
while(parserIterator.hasNext() && !endOfGroup) {
CSVRecord next = parserIterator.next();
System.out.println("getting input of " + next);
if (foundNextGroup(pendingRow, next)) {
endOfGroup = true;
System.out.println("found end of group");
}
else {
group.add(next);
}
pendingRow = Optional.of(next);
}
return group;
}
public boolean hasNext() {
return parserIterator.hasNext();
}
private boolean foundNextGroup(Optional<CSVRecord> maybeCurrent, CSVRecord next)
{
boolean foundNext = false;
if (maybeCurrent.isPresent()) {
CSVRecord current = maybeCurrent.get();
for(String column : pivotColumns) {
if(!current.get(column).equals(next.get(column))) {
System.out.println("column " + column + "does not match: [" + current.get(column) + "] [" +next.get(column) + "]");
foundNext = true;
}
}
}
return foundNext;
}
}
}