There are 2 csv:
1 - areaMap.csv
2 - currencyMap.csv
Enum AreaMapFromCsv
is the Singleton to store the Map<String, Enum>
read from 1 csv.
Enum CurrencyMapFromCsv
is the Singleton to store the Map<String, String>
read from 2 csv.
Interface IMapFromCsv
provides default method for reading Map
from csv.
AreaMapFromCsv
and CurrencyMapFromCsv
looks almost identical. They differs only in FILE_TO_LOAD
, argument passing to the interface default method and second type of Map parameters. Any ideas how to DRY?
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 IMapFromCsv{
public default <T> Map<String, T> getMap(String FILE_TO_LOAD, Function<String, T> convertValue){
Map<String, T> 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(tmp2[0], convertValue.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;
}
}
.
import java.util.Map;
import java.util.function.Function;
public enum AreaMapFromCsv implements IMapFromCsv {
INSTANCE;
final String FILE_TO_LOAD = "resources/areaMap.csv";
private Map<String, String> map;
private AreaMapFromCsv() {
init();
}
private void init() {
this.map = getMap(FILE_TO_LOAD, Function.identity());
}
public void reload() {
init();
}
public Map<String, String> get() {
return map;
}
}
.
import java.util.Map;
public enum CurrencyMapFromCsv implements IMapFromCsv {
INSTANCE;
final String FILE_TO_LOAD = "resources/currencyMap.csv";
private Map<String, Double> map;
private CurrencyMapFromCsv() {
init();
}
private void init() {
this.map = getMap(FILE_TO_LOAD, Double::parseDouble);
}
public void reload() {
init();
}
public Map<String, Double> get() {
return map;
}
}