代码之家  ›  专栏  ›  技术社区  ›  Vallas

将(yaml)文件转换为任何映射实现

  •  2
  • Vallas  · 技术社区  · 6 年前

    我在做一个业余项目,我需要从一个yaml文件中读取值并将它们存储在 HashMap ,另一个yaml文件必须存储在 LinkedHashMap . 我使用了一个API来进行阅读,下面的代码中添加了一些解释(尽管我认为这是非常多余的)。只有返回 链接地图 因为另一个几乎是相同的。

    目前我正在使用不同的方法来获取 哈希图 链接地图 但是注意到代码非常相似。所以我想知道,是否可以编写一个通用方法,将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文件,这在这个问题中是多余的。

    1 回复  |  直到 6 年前
        1
  •  2
  •   Lino    6 年前

    您可以利用功能接口(在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<>());
    

    同样,您希望使用什么映射实现,您可以根据自己的需要来决定。