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

Java 将(YAML)文件转换为任何映射实现,java,collections,hashmap,linkedhashmap,Java,Collections,Hashmap,Linkedhashmap,我在做一个业余项目,需要从YAML文件中读取值并将其存储在HashMap中,另一个YAML文件必须存储在LinkedHashMap中。我使用了一个API来进行阅读,下面的代码中添加了一些解释(尽管我认为这是非常多余的)。只包括返回LinkedHashMap的方法,因为另一个方法实际上是相同的 目前,我正在使用不同的方法获取HashMap和LinkedHashMap,但注意到代码非常相似。因此我想知道,是否可以编写一个通用方法,将YAML文件中的路径和值放入任何集合实现(正在实现哈希表)中?如果是

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

目前,我正在使用不同的方法获取
HashMap
LinkedHashMap
,但注意到代码非常相似。因此我想知道,是否可以编写一个通用方法,将YAML文件中的路径和值放入任何
集合
实现(正在实现
哈希表
)中?如果是这样的话,我们如何才能做到这一点呢

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;
}
public LinkedHashMap文件tolinkedhashmap(文件yamlFile)
{
LinkedHashMap fileContents=新建LinkedHashMap();
//我正在使用的API的一部分,读取YAML文件并存储内容
YamlConfiguration config=YamlConfiguration.loadConfiguration(yamlFile);
//配置#getKeys(true)获取读取文件中的所有路径
for(字符串路径:config.getKeys(true))
{
//获取路径的值
if(config.get(path)!=null)
put(路径,config.get(路径));
}
返回文件内容;
}

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

您可以使用功能接口(在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));
        }
    }
}
可以这样称呼:

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

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

可能在某个地方有一个dup,但不管怎样:很好的答案,很好的示例!
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<>());