我有一个csv文件,它定义了不同货币之间的关系。因此,要知道一种货币与另一种货币之间的关系,我决定使用Map的Map,其中key将是源货币名称,而值将再次是Map(键:目标货币名称,值:关系类型)。通过拥有这样的数据结构,我可以进行尾递归来查找源货币和目标货币之间的关系。
示例csv文件:
/ AUD CAD CNY CZK DKK EUR GBP JPY NOK NZD USD
AUD 1 USD USD USD USD USD USD USD USD USD D
CAD USD 1 USD USD USD USD USD USD USD USD D
CNY USD USD 1 USD USD USD USD USD USD USD USD D
要创建这样的数据结构,我在下面创建了方法,但它看起来太冗长了。所以我想知道是否已有的库可以解决我的目的。我尝试过apache常见的IO,但无法得到我想要的东西。
方法:
public static Map> generateCurrencyMatrix(
String currencyMatrixFilePath){
地图> currMatrixContext =
新的HashMap>();
映射termCurrencies = new HashMap();
// try with resources to close in case of exception
try (BufferedReader br = new BufferedReader(new FileReader(
currencyMatrixFilePath))) {
String line;
boolean headerLineIndicator = true;
while ((line = br.readLine()) != null) {
if (headerLineIndicator) {
List<String> termCurr = Arrays.asList(line
.split(Constant.delimiter));
IntStream.range(1, termCurr.size()).forEach(i -> {
termCurrencies.put(i, termCurr.get(i).trim());
});
headerLineIndicator = false;
} else {
List<String> relationship = Arrays.asList(line
.split(Constant.delimiter));
Map<String, String> relation = new HashMap<String, String>();
IntStream.range(1, relationship.size()).forEach(
i -> {
relation.put(termCurrencies.get(i).trim(),
relationship.get(i).trim());
});
currMatrixContext.put(relationship.get(0).trim(), relation);
}
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return currMatrixContext;
}
答案 0 :(得分:0)
以为我没有理解这个要求,我想你可以试试MultiValueMap。
答案 1 :(得分:0)
不知道你的目的是什么,如果这会帮助你达到目的,但你可以试试 https://commons.apache.org/proper/commons-csv/使用csv文件非常方便。