Java tutorial
//package com.java2s; import java.util.Calendar; import java.util.Date; import java.util.HashMap; public class Main { public static HashMap<Integer, HashMap<Integer, Integer>> getAvailableTime(HashMap<Date, Date> bookedTimes, Date date) { HashMap<Integer, HashMap<Integer, Integer>> availableTime = createFullAvailableTime(); HashMap<Date, Date> bookedTimeInOneDate = getBookedTimeInOneDate(bookedTimes, date); Calendar startCalendar = Calendar.getInstance(); Calendar endCalendar = Calendar.getInstance(); for (Date keyBooked : bookedTimeInOneDate.keySet()) { startCalendar.setTime(keyBooked); int startHour = startCalendar.get(Calendar.HOUR_OF_DAY); for (int hourIndex = 0; hourIndex < 24; hourIndex++) { if (hourIndex == startHour) { int startMinute = startCalendar.get(Calendar.MINUTE); int endMinute; endCalendar.setTime(bookedTimeInOneDate.get(keyBooked)); int endHour = endCalendar.get(Calendar.HOUR_OF_DAY); //startHour = endHour = hourIndex if (endHour == hourIndex) { endMinute = endCalendar.get(Calendar.MINUTE); removeMinute(startMinute, endMinute, hourIndex, availableTime); } //startHour = hourIndex != endHour else { for (int i = hourIndex; i < endHour + 1; i++) { if (i == hourIndex) { if (startMinute == 0) { availableTime.remove(startHour); } else { removeMinute(startMinute, 59, hourIndex, availableTime); } } else if (i == endHour) { endMinute = endCalendar.get(Calendar.MINUTE); if (endMinute == 59) { availableTime.remove(endHour); } else { removeMinute(0, endMinute, endHour, availableTime); } } else { availableTime.remove(i); } } } } } } return availableTime; } private static HashMap<Integer, HashMap<Integer, Integer>> createFullAvailableTime() { HashMap<Integer, HashMap<Integer, Integer>> availableTime = new HashMap<>(); for (int hour = 0; hour < 24; hour++) { HashMap<Integer, Integer> minutes = new HashMap<>(60); for (int minute = 0; minute < 60; minute++) { minutes.put(minute, minute); } availableTime.put(hour, minutes); } return availableTime; } private static HashMap<Date, Date> getBookedTimeInOneDate(HashMap<Date, Date> bookedTimes, Date date) { HashMap<Date, Date> result = new HashMap<>(); for (Date key : bookedTimes.keySet()) { if (isSameDay(key, date)) { result.put(key, bookedTimes.get(key)); } } return result; } private static HashMap<Integer, HashMap<Integer, Integer>> removeMinute(int startMinute, int endMinute, int keyHour, HashMap<Integer, HashMap<Integer, Integer>> hashMap) { HashMap<Integer, Integer> values = hashMap.get(keyHour); for (int i = startMinute; i < endMinute + 1; i++) { values.remove(i); } // hashMap.remove(keyHour); // hashMap.put(keyHour, values); return hashMap; } public static boolean isSameDay(Date date1, Date date2) { Calendar cal1 = Calendar.getInstance(); Calendar cal2 = Calendar.getInstance(); cal1.setTime(date1); cal2.setTime(date2); boolean sameDay = cal1.get(Calendar.YEAR) == cal2.get(Calendar.YEAR) && cal1.get(Calendar.DAY_OF_YEAR) == cal2.get(Calendar.DAY_OF_YEAR); return sameDay; } }