1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
|
public class Solution {
public Map<String, Object> flatten(Map<String, Object> dict) {
Map<String, Object> ans = new HashMap<>();
flattenHelper("", dict, ans);
return ans;
}
private void flattenHelper(String prefix, Map<String, Object> dict, Map<String, Object> ans) {
for (Map.Entry<String, Object> entry : dict.entrySet()) {
String key = entry.getKey();
Object value = entry.getValue();
String newKey = prefix.isEmpty() ? key : prefix + "." + key;
if (value instanceof Map) {
flattenHelper(newKey, (Map) value, ans);
} else {
ans.put(newKey, value);
}
}
}
public static void main(String[] args) {
Solution solution = new Solution();
Map<String, Object> input = new HashMap<>();
Map<String, Object> foo = new HashMap<>();
Map<String, Object> bar = new HashMap<>();
bar.put("baz", 8);
foo.put("a", 5);
foo.put("bar", bar);
input.put("key", 3);
input.put("foo", foo);
Map<String, Object> result = solution.flatten(input);
System.out.println(result); // Output: {key=3, foo.a=5, foo.bar.baz=8}
}
}
|