java 31 lines · 7 steps

Flattening nested maps into dotted keys

A recursive walk turns nested maps and lists into a flat map whose keys encode the full path to each value.

Explained by highlit
1public final class MapFlattener {
2 
3 private MapFlattener() {
4 }
5 
6 public static Map<String, Object> flatten(Map<String, Object> source) {
7 Map<String, Object> result = new LinkedHashMap<>();
8 flattenInto(null, source, result);
9 return result;
10 }
11 
12 private static void flattenInto(String prefix, Map<String, Object> source, Map<String, Object> target) {
13 for (Map.Entry<String, Object> entry : source.entrySet()) {
14 String key = prefix == null ? entry.getKey() : prefix + "." + entry.getKey();
15 appendValue(key, entry.getValue(), target);
16 }
17 }
18 
19 @SuppressWarnings("unchecked")
20 private static void appendValue(String key, Object value, Map<String, Object> target) {
21 if (value instanceof Map<?, ?> nested) {
22 flattenInto(key, (Map<String, Object>) nested, target);
23 } else if (value instanceof List<?> list) {
24 for (int i = 0; i < list.size(); i++) {
25 appendValue(key + "[" + i + "]", list.get(i), target);
26 }
27 } else {
28 target.put(key, value);
29 }
30 }
31}
01 / 01
STEP 01

Walkthrough

Space play step click any line
Three takeaways
  1. 1Building a path prefix as you descend lets you express deep structure as flat, self-describing keys.
  2. 2Two mutually recursive helpers — one for maps, one for individual values — cleanly separate iteration from type dispatch.
  3. 3A LinkedHashMap preserves the insertion order of the flattened output, keeping keys in a predictable, readable sequence.

Related explainers

Share this explainer

Here's the card — post it anywhere.

Flattening nested maps into dotted keys — share card
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code