I have a nested HashMap
with String
keys that contains either List
, Map
, or String
values. I would like to flatten them like the below.
Here is the data:
import java.util.*;
import java.util.stream.*;
public class MyClass {
public static void main(String args[]) {
Map<String, Object> dates = new HashMap<String, Object>() {{
put("1999", new HashMap<String, Object>() {{
put("3", Arrays.asList("23", "24", "25"));
put("4", Arrays.asList("1", "2", "3"));
}});
put("2001", new HashMap<String, Object>() {{
put("11", new HashMap<String, Object>() {{
put("7", Arrays.asList("23", "24", "25"));
put("9", Arrays.asList("1", "2", "3"));
}});
put("12", "45");
}});
}};
System.out.println(dates);
}
}
Map looks like:
{2001={11={7=[23, 24, 25], 9=[1, 2, 3]}, 12=45},
1999={3=[23, 24, 25], 4=[1, 2, 3]}}
The flattening of map should look like this:
{2001.11.7.1=23, 2001.11.7.2=24, 2001.11.7.3=25, 2001.11.9.1=1, 2001.11.9.2=2,
2001.11.9.3=3, 2001.12=45, 1999.3.1=23, 1999.3.2=24, 1999.3.3=25,
1999.4.1=1, 1999.4.2=2, 1999.4.3=3}
Note: the level of nested arrays or maps is unknown, it may go more than 2 levels.