【问题标题】:Converting a (YAML) file to any MAP implementation将 (YAML) 文件转换为任何 MAP 实现
【发布时间】:2019-06-08 18:52:14
【问题描述】:

我正在从事一个业余项目,我需要从 YAML 文件中读取值并将它们存储在 HashMap 中,另一个 YAML 文件必须存储在 LinkedHashMap 中。我使用了一个 API 来进行阅读,在下面的代码中添加了一些解释(尽管我认为这很多余)。仅包含返回 LinkedHashMap 的方法,因为另一个实际上是相同的。

目前我正在使用单独的方法来获取HashMapLinkedHashMap,但注意到代码非常相似。所以我想知道,是否可以编写一个通用方法,将 YAML 文件中的路径和值放入任何Collections 实现(正在实现Hash Table)?如果是这样,怎么能做到这一点?

public LinkedHashMap<String, Object> fileToLinkedHashMap(File yamlFile)
{
    LinkedHashMap<String, Object> fileContents = new LinkedHashMap<String, Object>();

    //Part of the API I'm using, reads from YAML File and stores the contents
    YamlConfiguration config = YamlConfiguration.loadConfiguration(yamlFile);

    //Configuration#getKeys(true) Gets all paths within the read File
    for (String path : config.getKeys(true))
    {
        //Gets the value of a path
        if (config.get(path) != null)
            fileContents.put(path, config.get(path));
    }

    return fileContents;
}

注意:我知道我目前没有检查给定文件是否是 YAML 文件,这在这个问题中是多余的。

【问题讨论】:

    标签: java collections hashmap linkedhashmap


    【解决方案1】:

    您可以为此使用函数式接口(在 java 8 中引入):

    public void consumeFile(File yamlFile, BiConsumer<? super String, ? super Object> consumer){
        YamlConfiguration config = YamlConfiguration.loadConfiguration(yamlFile);
        for (String path : config.getKeys(true)){
            if (config.get(path) != null){
                consumer.accept(path, config.get(path));
            }
        }
    }
    

    然后可以用任何东西来调用它,你只需要提供一个接受 2 个参数的 lambda:

    // collect into a map
    Map<String, Object> map = /* hash map, linked hash map, tree map, you decide */;
    consumeFile(yamlFile, map::put);
    
    // just print them, why not?
    consumeFile(yamlFile, (key, value) -> System.out.println(key + " = " + value));
    

    你看,用途可能是无穷无尽的。仅受您的用例和想象力的限制。

    如果你不能使用 java 8(你可能应该),还是有希望的。当您两次都返回Map 时,您可以决定在调用该方法时要收集到哪个地图实现:

    public Map<String, Object> consumeFile(File yamlFile, Map<String, Object> map){
        YamlConfiguration config = YamlConfiguration.loadConfiguration(yamlFile);
        for (String path : config.getKeys(true)){
            if (config.get(path) != null){
                map.put(path, config.get(path));
            }
        }
        return map;
    }
    

    可以这样称呼:

    Map<String, Object> map = consumeFile(yamlFile, new /*Linked*/HashMap<>());
    

    同样,您要使用哪种地图实现,您可以根据自己的需要来决定。

    【讨论】:

    • 可能在某个地方有一个 dup,但无论如何:很好的答案,很好的例子!
    猜你喜欢
    • 2020-09-23
    • 2012-08-13
    • 1970-01-01
    • 2011-06-22
    • 1970-01-01
    • 2012-10-12
    • 2021-07-21
    • 1970-01-01
    • 2018-12-04
    相关资源
    最近更新 更多