java - 将 (YAML) 文件转换为任何 MAP 实现

标签 java collections hashmap linkedhashmap

我在做一个业余项目,我需要从 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 文件,这在这个问题中是多余的。

最佳答案

您可以为此使用功能接口(interface)(在 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 时,您可以决定在调用该方法时您希望将哪个 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<>());

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

关于java - 将 (YAML) 文件转换为任何 MAP 实现,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54187358/

相关文章:

java - getElementById 出现空指针异常

java - Vaadin:以编程方式打开组合框下拉菜单

Java,如何遍历 Collection<?延伸 E>?

java - Android:将ListView数据存储在Hashmap<String, String>的ArrayList中

java - 列表值被新值替换

java - 从 Spring 2.5.6 升级到 3.2.6 导致 Spring Transaction Management 不再适用于 JBoss 5.1.0 和 Hibernate 3.5.6

java - 启动期间 IntelliJ java.lang.ClassNotFoundException : com. intellij.ide.plugins.PluginManager

c# - 从两个列表c#中获取匹配项的最快方法

collections - 如何组合列表元素并找到最大组合的价格

Java 哈希表存储桶作为 ArrayList