您可以利用功能接口(在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<>());
同样,您希望使用什么映射实现,您可以根据自己的需要来决定。