HI I have a csv called test.csv
. I am trying to read the csv line by line and convert the values into a hash key value pairs .
Here is the code :-
Using FasterXML's CSV package: https://github.com/FasterXML/jackson-dataformats-text/tree/master/csv
public static List<Map<String, String>> read(File file) throws JsonProcessingException, IOException {
List<Map<String, String>> response = new LinkedList<Map<String, String>>();
CsvMapper mapper = new CsvMapper();
CsvSchema schema = CsvSchema.emptySchema().withHeader();
MappingIterator<Map<String, String>> iterator = mapper.reader(Map.class)
.with(schema)
.readValues(file);
while (iterator.hasNext()) {
response.add(iterator.next());
}
return response;
}
The problem is that when you split
your str
, the first element in each line is alone (i.e 1 and 2). So arr
only contains ["1"]
, and hence arr[1]
doesn't exists.
I.e for the example input :
1,"testCaseName":"ACLTest"
split by ,
=> str
contains {1, testCaseName:ACLTest}
split by :
at the first iteration => arr contains {1}
Example :
String s = "1,testCaseName:ACLTest";
String str[] = s.split(",");
System.out.println(Arrays.toString(str));
for(String p : str){
String arr[] = p.split(":");
System.out.println(Arrays.toString(arr));
}
Output :
[1, testCaseName:ACLTest]
[1] //<- here arr[1] doesn't exists, you only have arr[0] and hence the ArrayIndexOutOfBoundsException when trying to access arr[1]
[testCaseName, ACLTest]
for(int i=1;i<str.length;i++){
String arr[] = str[i].split(":");
map.put(arr[0], arr[1]);
}
HashMap
use the hashCode
of the keys to store the (key, value) pairs.
So when insering "testCaseName":"ACLTest"
and "testCaseName":"DCLAddTest"
, the first value will be erased and replace by the second one :
Map<String, String> map = new HashMap<>();
map.put("testCaseName","ACLTest");
map.put("testCaseName","DCLAddTest");
System.out.println(map);
Output :
{testCaseName=DCLAddTest}
So you have to fix that too.