【问题标题】:Java csv library to create Map of Map given a relationship matrixJava csv 库在给定关系矩阵的情况下创建 Map 的 Map
【发布时间】:2018-01-10 11:55:06
【问题描述】:

我有一个 csv 文件,它定义了不同货币之间的关系。因此,为了了解一种货币与另一种货币之间的关系,我决定使用 Map 的 Map,其中键将是源货币名称,值将再次是 Map(键:目标货币名称,值:关系类型)。通过拥有这样的数据结构,我可以进行尾递归来查找源货币和目标货币之间的关系。

示例 csv 文件:
/ AUD CAD CNY CZK DKK EUR GBP JPY NOK NZD USD
澳元 1 美元 美元 美元 美元 美元 美元 美元 美元 美元 D
CAD 美元 1 美元 美元 美元 美元 美元 美元 美元 美元 D
人民币 美元 美元 1 美元 美元 美元 美元 美元 美元 美元 D

为了创建这样的数据结构,我创建了下面的方法,但它看起来太冗长了。所以我想知道是否已经存在可以解决我的目的的库。我尝试了 apache common IO,但找不到我想要的东西。 方法:
公共静态地图> generateCurrencyMatrix( 字符串 currencyMatrixFilePath) { 地图> currMatrixContext = 新的哈希映射>(); 映射 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;
}

【问题讨论】:

  • 该地图的参数化版本看起来像 Map> 上下文吗?其中键是 columnName 而值是列?然后由关系向后引用为关系,其中值是列中的键,键在值中?

标签: java csv


【解决方案1】:

以为我没看懂需求,我觉得你可以试试MultiValueMap。

【讨论】:

    【解决方案2】:

    不知道你的目的是什么,如果这能帮助你实现它,但你可以试试
    https://commons.apache.org/proper/commons-csv/ 处理 csv 文件非常方便。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-07-12
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多