Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save JamieCressey/b1003651844fe938a4ddba18c607ce79 to your computer and use it in GitHub Desktop.
Save JamieCressey/b1003651844fe938a4ddba18c607ce79 to your computer and use it in GitHub Desktop.
Java POJO to dot notation
public class FlattenedMapEntry {
String key;
String value;
}
public static List<FlattenedMapEntry> flattenMap(String parent, Map<?, ?> map) {
List<FlattenedMapEntry> results = new ArrayList<>();
for (Object o : map.entrySet()) {
Map.Entry pair = (Map.Entry) o;
String key;
if (parent == null) {
key = pair.getKey().toString();
} else {
key = parent + "." + pair.getKey().toString();
}
if (pair.getValue() instanceof Map<?, ?>) {
results.addAll(flattenMap(key, (Map<?, ?>) pair.getValue()));
} else if (pair.getValue() instanceof Set<?> || pair.getValue() instanceof List<?>) {
List<?> list = (List<?>) pair.getValue();
for (Object aList : list) {
if (aList instanceof Map<?, ?>) {
results.addAll(flattenMap(key, (Map<?, ?>) aList));
} else {
results.add(FlattenedMapEntry.builder().key(key + "." + aList.toString()).value("").build());
}
}
} else if (pair.getValue() != null) {
String value = pair.getValue().toString();
results.add(FlattenedMapEntry.builder().key(key).value(value).build());
}
}
return results;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment