Created
September 4, 2019 20:30
-
-
Save pbatey/4113ca593c181c94bc9c9f98972abe56 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Unit Test here: https://gist.github.com/pbatey/c8381d3b1e529c5a611a84909c8733ee