forked from oleg-cherednik/DailyCodingProblem
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSolution.java
42 lines (33 loc) · 1.23 KB
/
Solution.java
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
37
38
39
40
41
42
import java.util.Collections;
import java.util.LinkedHashMap;
import java.util.Map;
/**
* @author Oleg Cherednik
* @since 28.05.2019
*/
public class Solution {
public static void main(String... args) {
Map<String, Object> foo = new LinkedHashMap<>();
foo.put("a", 5);
foo.put("bar", Collections.singletonMap("baz", 8));
Map<String, Object> dic = new LinkedHashMap<>();
dic.put("key", 3);
dic.put("foo", foo);
Map<String, String> map = flatten(dic);
map.forEach((key, value) -> System.out.println(key + ": " + value));
}
public static Map<String, String> flatten(Map<String, Object> dic) {
return flatten(null, dic, new LinkedHashMap<>());
}
private static Map<String, String> flatten(String prefix, Map<String, Object> dic, Map<String, String> map) {
for (Map.Entry<String, Object> entry : dic.entrySet()) {
String key = prefix == null ? entry.getKey() : prefix + '.' + entry.getKey();
Object value = entry.getValue();
if (value instanceof Map)
flatten(key, (Map<String, Object>)value, map);
else
map.put(key, String.valueOf(value));
}
return map;
}
}