I have a multi-nested LinkedHashMap, read from a YAML file, and I want to update the keys of the multi-nested LinkedHashMap with the Values of another multi-nested LinkedHashMap, on the equivalent Key.
I have gone through this and this but no solution yet.
Here is my code entry point (main method)
public static void main(String[] args) {
Yaml yaml = new Yaml();
InputStream inputStream = YamlParser.class
.getClassLoader()
.getResourceAsStream("application.yaml");
InputStream readIs = YamlParser.class
.getClassLoader()
.getResourceAsStream("rename.yaml");
LinkedHashMap<String, Object> mainObj = yaml.load(inputStream);
LinkedHashMap<String, Object> renameYamlObj = yaml.load(readIs);
LinkedHashMap<String, Object> newObj = new LinkedHashMap<>();
start(renameYamlObj, mainObj, newObj);
System.out.println(resultantMap);
}
Here is the first loop method
private static void start(
LinkedHashMap<String, Object> renameYamlObj,
LinkedHashMap<String, Object> mainObj,
LinkedHashMap<String, Object> newObj) {
for (Map.Entry<String, Object> entry : renameYamlObj.entrySet()) {
if (entry.getValue() instanceof LinkedHashMap) {
start((LinkedHashMap<String, Object>) entry.getValue(), mainObj, newObj);
} else {
System.out.println("entry.getValue() " + entry.getValue());
copyAndRenameKeys(mainObj, newObj, entry.getKey(), entry.getValue().toString());
}
}
}
Here is the second loop method
//copy and update multi level map to another map
private static void copyAndRenameKeys(
LinkedHashMap<String, Object> mainObj,
LinkedHashMap<String, Object> newObj,
String oldKey, String newKey) {
for (Map.Entry<String, Object> entry : mainObj.entrySet()) {
if (!(entry.getValue() instanceof LinkedHashMap)) {
if (entry.getKey().equals(oldKey)) {
newObj.put(newKey, entry.getValue());
System.out.println("Main obj: " + mainObj);
System.out.println("New Obj: " + newObj);
System.out.println(" ");
} else {
continue;
}
break;
} else {
LinkedHashMap<String, Object> newSub = new LinkedHashMap<>();
copyAndRenameKeys((LinkedHashMap<String, Object>) entry.getValue(), newSub, oldKey, newKey);
newObj.put(entry.getKey(), newSub);
System.out.println("Main obj: " + mainObj);
System.out.println("New Obj: " + newObj);
System.out.println(" ");
}
}
}
Expect output
Main obj: {metadata={name=deployment, labels={application=application}}}
New Obj: {metadata={newname=deployment, labels={newapplication=application}}}
Actual output
Main obj: {metadata={name=deployment, labels={application=application}}}
New Obj: {metadata={labels={newapplication=application}}}
What am I doing wrong?