【发布时间】:2019-06-08 18:52:14
【问题描述】:
我正在从事一个业余项目,我需要从 YAML 文件中读取值并将它们存储在 HashMap 中,另一个 YAML 文件必须存储在 LinkedHashMap 中。我使用了一个 API 来进行阅读,在下面的代码中添加了一些解释(尽管我认为这很多余)。仅包含返回 LinkedHashMap 的方法,因为另一个实际上是相同的。
目前我正在使用单独的方法来获取HashMap 和LinkedHashMap,但注意到代码非常相似。所以我想知道,是否可以编写一个通用方法,将 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