fork download
  1. import java.util.*;
  2. public class Main {
  3. @SuppressWarnings("serial")
  4. public static void main(String[] args) {
  5. final Map<String, Object> dates = new HashMap<String, Object>() {
  6. {
  7. put("1999", new HashMap<String, Object>() {
  8. {
  9. put("3", Arrays.asList("23", "24", "25"));
  10. put("4", Arrays.asList("1", "2", "3"));
  11. }
  12. });
  13. put("2001", new HashMap<String, Object>() {
  14. {
  15. put("11", new HashMap<String, Object>() {
  16. {
  17. put("7", Arrays.asList("23", "24", "25"));
  18. put("9", Arrays.asList("1", "2", "3"));
  19. }
  20. });
  21. put("12", "45");
  22. }
  23. });
  24. }
  25. };
  26. final Map<String, Object> flattened = flatten(dates);
  27. System.out.println(flattened);
  28. }
  29.  
  30. public static Map<String, Object> flatten(final Map<String, Object> map) {
  31. return flatten("", map, new HashMap<>());
  32. // use new TreeMap<>() to order map based on key
  33. }
  34.  
  35. @SuppressWarnings("unchecked")
  36. private static Map<String, Object> flatten(final String key, final Map<String, Object> map,
  37. final Map<String, Object> result) {
  38. final Set<Map.Entry<String, Object>> entries = map.entrySet();
  39. if (!entries.isEmpty()) {
  40. for (final Map.Entry<String, Object> entry : entries) {
  41. final String currKey = key + (key.isEmpty() ? "" : '.') + entry.getKey();
  42. final Object value = entry.getValue();
  43. if (value instanceof Map) {
  44. flatten(currKey, (Map<String, Object>) value, result);
  45. } else if (value instanceof List) {
  46. final List<Object> list = (List<Object>) value;
  47. for (int i = 0, size = list.size(); i < size; i++) {
  48. result.put(currKey + '.' + (i + 1), list.get(i));
  49. }
  50. } else {
  51. result.put(currKey, value);
  52. }
  53. }
  54. }
  55. return result;
  56. }
  57. }
Success #stdin #stdout 0.12s 36704KB
stdin
Standard input is empty
stdout
{1999.3.2=24, 1999.4.1=1, 1999.3.1=23, 1999.4.3=3, 2001.12=45, 1999.3.3=25, 1999.4.2=2, 2001.11.7.1=23, 2001.11.9.2=2, 2001.11.9.3=3, 2001.11.7.2=24, 2001.11.7.3=25, 2001.11.9.1=1}