-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathCsvParser.java
More file actions
101 lines (77 loc) · 2.71 KB
/
CsvParser.java
File metadata and controls
101 lines (77 loc) · 2.71 KB
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
90
91
92
93
94
95
96
97
98
99
100
101
package com.pubfactory.test;
import com.sun.xml.internal.xsom.impl.scd.Iterators;
import java.util.*;
// The solution setup is where you can provide the candidate with the basic framework for their solution.
public class CsvParser {
/**
* Creates the parser with the CSV file to parse.
*
* @param file the CSV file to parse
*/
Map<String, List> csvMatrix = new HashMap<String, List>();
public CsvParser(String file) {
super();
List<String> lines = Arrays.asList(file.split("\n"));
List<String> headers = Arrays.asList(lines.get(0).split(","));
List<String> linesParse = new ArrayList<>();
List<String> aux = new ArrayList<>();
int j = 0;
int k = 0;
for (String line : lines) {
if (line.contains(lines.get(0))) {
continue;
}
if (j == 0) {
for (String i : headers) {
linesParse = Arrays.asList(line.split(","));
aux = new ArrayList<>(Arrays.asList(linesParse.get(k)));
csvMatrix.put(i, aux);
k++;
}
j++;
k = 0;
continue;
}
linesParse = Arrays.asList(line.split(","));
for (String i : headers) {
if (k < headers.size()) {
List<String> aux1 = csvMatrix.get(i);
aux1.add(linesParse.get(k));
csvMatrix.put(i, aux1);
k++;
}
}
k = 0;
}
System.out.println(csvMatrix);
}
/**
* Returns the value of a specific cell.
* <p>
* DO NOT CHANGE THIS METHOD SIGNATURE
*
* @param columnName the exact name of the column
* @param rowIndex the 0-based index of the row not including the column header row
* @return the cell value
* @throws IllegalArgumentException if columnName does not match a column
* @throws IndexOutOfBoundsException if rowIndex < 0 or > # of rows - 1
*/
public String getCellValue(String columnName, int rowIndex) throws Exception { // was IOException
if (rowIndex == 0) {
rowIndex = 1;
}
if(rowIndex < 0){
throw new IllegalArgumentException();
}
if (csvMatrix.containsKey(columnName)) {
List<String> column = csvMatrix.get(columnName);
if (rowIndex > column.size() - 1) {
throw new IndexOutOfBoundsException();
} else {
return column.get(rowIndex - 1);
}
} else {
throw new IllegalArgumentException();
}
}
}