Skip to content

Instantly share code, notes, and snippets.

@pbatey
Created September 4, 2019 20:30
Show Gist options
  • Save pbatey/4113ca593c181c94bc9c9f98972abe56 to your computer and use it in GitHub Desktop.
Save pbatey/4113ca593c181c94bc9c9f98972abe56 to your computer and use it in GitHub Desktop.
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Vector;
/**
* Flattens a Map
*/
public class Flattener {
static public void process(Map<String, Object> target) {
process(target, "");
}
static public void process(Map<String, Object> target, String prefix) {
List<String> removeKeys = new Vector<>();
Map<String, Object> flattened = new HashMap<>();
target.forEach((k, v) -> {
if (v instanceof Map) {
Map<String, Object> m = (Map<String, Object>) v;
process(m, prefix + k + "_");
m.forEach((mk,mv) -> flattened.put(mk, mv));
removeKeys.add(k);
} else if (v instanceof List) {
flattened.put(prefix + k + "_count", ((List) v).size());
removeKeys.add(k);
} else {
flattened.put(prefix + k, v);
if (prefix.length() > 0) removeKeys.add(k);
}
});
removeKeys.forEach(k -> target.remove(k));
target.putAll(flattened);
}
}
@pbatey
Copy link
Author

pbatey commented Sep 4, 2019

Flattens a hierarchical object (usually from JSON) into a flat structure. Arrays are summarized by counting entries.

Useful when summarizing hierarchical objects as a single relational database table (assuming structure matches a consistent schema).

@pbatey
Copy link
Author

pbatey commented Sep 4, 2019

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment