CSV file into variable in order. I've been trying to read a CSV file which contains two columns, a title and then a list of entries.
Currently I've been using a LinkedHashMap; using the following loop to read, split and create the LinkedHashMap.
However it currently gets stuck on line 5 of my CSV. Here's the current read loop:
public static LinkedHashMap<String, ArrayList<String>> runningOrderMap(String filename) throws IOException {
LinkedHashMap<String, ArrayList<String>> linkedHashMap = new LinkedHashMap<>(50);
String currentLine = ""; //init iterator variable
String[] valuesTMP;
try {
bufferedReader = new BufferedReader(new FileReader(filename));
} catch (FileNotFoundException e) {
e.printStackTrace();
}
while((currentLine = bufferedReader.readLine()) != null){
valuesTMP = currentLine.split(", ");
ArrayList<String> values = new ArrayList<>();
String key = valuesTMP[0].split("\t")[0].trim();
values.add(valuesTMP[0].split("\t")[1].trim());
for(int i = 1; i < valuesTMP.length; i++){
values.add(valuesTMP[i]);
System.out.println(valuesTMP[i]);
linkedHashMap.put(key, values);
}
}
System.out.println("linked hashmap:"+linkedHashMap.keySet().size());
return linkedHashMap;
}
the example data is formatted as such, title which varies in length, a tab, then a list of content entries like that:
title content, content2
title example content, content2, content3
title example three content, content2
title example content, content2
and this data goes on for about 20 lines, however the LinkedHashMap will not go past line 5:
title example two content
I need to preserve the line order in the array.
It seems I know what is wrong)
Try to move line linkedHashMap.put(key, values);
out of internal for
loop, like this:
public static LinkedHashMap<String, ArrayList<String>> runningOrderMap(String filename) throws IOException {
LinkedHashMap<String, ArrayList<String>> linkedHashMap = new LinkedHashMap<>(50);
String currentLine = ""; //init iterator variable
String[] valuesTMP;
try {
bufferedReader = new BufferedReader(new FileReader(filename));
} catch (FileNotFoundException e) {
e.printStackTrace();
}
while((currentLine = bufferedReader.readLine()) != null){
valuesTMP = currentLine.split(", ");
ArrayList<String> values = new ArrayList<>();
String key = valuesTMP[0].split("\t")[0].trim();
values.add(valuesTMP[0].split("\t")[1].trim());
for(int i = 1; i < valuesTMP.length; i++){
values.add(valuesTMP[i]);
System.out.println(valuesTMP[i]);
}
linkedHashMap.put(key, values); // <--this line was moved out from internal for loop
}
System.out.println("linked hashmap:"+linkedHashMap.keySet().size());
return linkedHashMap;
}
Because, you see, this internal for
loop is executed only if there are more than one parts of content