Consider I have a String
:
String value = "Sunday - H15,Sunday - H03,Sunday - H13,Sunday - H01,Sunday - H05,Friday - H23,Saturday - H05,Monday - H16,Monday - H17,Monday - H18,Monday - H19,Monday - H20";
In this String
we have Day
s (Sunday, Monday etc..) and the alphanumeric (H15, H03 etc..) is hours.
Now I want a JSON format for Map<String, Map<String, List<String>>>
in which Key should be Day
and Value should be the Map having Key as Hours and Values as list of Hours which has same day. Something like this format:
{"Monday":{"Hours":["H16","H17","H18","H19","H20"]},"Thursday":{"Hours":[]},"Friday":{"Hours":["H23"]},"Sunday":{"Hours":["H15","H03","H13","H01","H05"]},"Wednesday":{"Hours":[]},"Tuesday":{"Hours":[]},"Saturday":{"Hours":["H05"]}}
Note: In this example there are some days with valid hours (like Sunday, Monday etc) while other are having empty Hours (like Wednesday and Thursday).
This code is working fine as required but I feel that it can be refactored.
public class DayPartProcessingTest {
public static void main(String[] args) throws JsonProcessingException {
String propertyValue = "Sunday - H15,Sunday - H03,Sunday - H13,Sunday - H01,Sunday - H05,Friday - H23,Saturday - H05,Monday - H16,Monday - H17,Monday - H18,Monday - H19,Monday - H20";
Map<String, List<String>> map = new HashMap<String, List<String>>();
String[] dayParts = propertyValue.split(",");
for (String string : dayParts) {
String[] array = string.split(" - ");
if (map.get(array[0]) == null) {
List<String> list = new ArrayList<>();
list.add(array[1]);
map.put(array[0], list);
} else {
List<String> tempList = map.get(array[0]);
tempList.add(array[1]);
map.put(array[0], tempList);
}
}
Map<String, Map<String, List<String>>> payload = new HashMap<>();
Map<String, List<String>> hrs1 = new HashMap<>();
hrs1.put("Hours", new ArrayList<String>());
payload.put("Sunday", hrs1);
payload.put("Monday", hrs1);
payload.put("Tuesday", hrs1);
payload.put("Wednesday", hrs1);
payload.put("Thursday", hrs1);
payload.put("Friday", hrs1);
payload.put("Saturday", hrs1);
for (Entry<String, List<String>> entry : map.entrySet()) {
Map<String, List<String>> hrs = new HashMap<>();
hrs.put("Hours", entry.getValue());
if (payload.containsKey(entry.getKey())) {
payload.put(entry.getKey(), hrs);
}
}
String json = new ObjectMapper().writeValueAsString(payload);
System.out.println(json);
}
Map<String, List<String>>
? There's no point in having a map with a single key. \$\endgroup\$