I was working on a spare time project where I needed to read values from a YAML file and store them in a HashMap, another YAML file had to be stored in a LinkedHashMap. I used an API to do the reading, some explanation was added in the code below (though I believe it's quite redundant). Only the method that returns a LinkedHashMap was included because the other one is practically identical.
Currently I'm using seperate methods for getting a HashMap and LinkedHashMap but noticed that the code was quite similar. So I wondered, would it be possible to write a general method that puts the paths and values from the YAML file into any Collections implementation (that are implementing Hash Table)? And if so, how could one accomplish that?
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;
}
Note: I know I'm currently not checking if the given file is a YAML file, this is redundant within this question.