I want to have 2 classes responsible for reading dictionaries from CSV.
The 1st class takes 2 columns from CSV and makes Map<String, String>
.
The 2nd class takes 2 columns from CSV and makes Map<String, Double>
.
I want to solve it according to DRY rule so I've made a generic method for making Map<T1, T2>
from csv which will be used by 1st class and 2nd class. It goes like this:
package Main;
import java.io.File;
import java.io.FileNotFoundException;
import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;
import java.util.function.Function;
public interface MapFromCsv<T1, T2> {
public default Map<T1, T2> getMap(String FILE_TO_LOAD, Function<String, T1> foo1, Function<String, T2> foo2){
Map<T1, T2> mapResult = new HashMap<>();
File f = new File(FILE_TO_LOAD);
try (Scanner sc = new Scanner(f)) {
while (sc.hasNextLine()) {
String tmp = sc.nextLine();
String[] tmp2 = tmp.split(";");
mapResult.put((T1) foo1.apply(tmp2[0]), (T2) foo2.apply(tmp2[1]));
}
} catch (FileNotFoundException fntf) {
System.err.println("File " + f.getPath() + "was not found.");
} catch (Exception e) {
System.err.println("Something went wrong with reading " + f.getPath());
}
return mapResult;
}
}
and implementation of the first class for making Map<String, String>
goes like this:
package Main;
import java.util.Map;
public enum StringMapFromCsv implements MapFromCsv<String, String> {
INSTANCE;
final String FILE_TO_LOAD = "resources/stringMap.csv";
private Map<String, String> stringMap;
private StringMapFromCsv() {
initStringMap();
}
private void initStringMap() {
this.stringMap = getMap(FILE_TO_LOAD);
}
public void reloadStringMap() {
initStringMap();
}
public Map<String, String> getStringMap() {
return stringMap;
}
}
and implementation of the second class for making Map<String, Double>
goes like this:
package Main;
import java.util.Map;
public enum DoubleMapFromCsv implements MapFromCsv<String, Double>{
INSTANCE;
final String FILE_TO_LOAD = "resources/doubleMap.csv";
private Map<String, Double> doubleMap;
private DoubleMapFromCsv() {
initDoubleMap();
}
private void initDoubleMap() {
this.doubleMap = getMap(FILE_TO_LOAD);
}
public void reloadDoubleMap() {
initDoubleMap();
}
public Map<String, Double> getDoubleMap() {
return doubleMap;
}
}
Anu suggestions?