Reputation: 749
I am trying to do something like below. I don't like the design of this as I am using 4 for loops to achieve this. Can I further enhance the design to achieve this?
Creating a map with dates as keys.
Sort the list values inside the map on dates(dates have hours and minutes here)
Giving an incremental id to each dto.
int serialNumber = 1;
if (hList != null && !hList.isEmpty()) {
// create a Map with dates as keys
HashMap<String, ArrayList<BookDTO>> mapObj = new HashMap<>();
for (int count = 0; count < hList.size(); count++) {
BookDTO bookDTO = (BookDTO) hList.get(count);
ArrayList<BookDTO> list = new ArrayList<>();
list.add(bookDTO);
Calendar depDate = bookDTO.getDepartureDate();
SimpleDateFormat format = new SimpleDateFormat("dd-MM-yyyy");
if (depDate != null) {
String formattedDate = format.format(depDate.getTime());
if (mapObj.containsKey(formattedDate)) {
mapObj.get(formattedDate).add(bookDTO);
} else {
mapObj.put(formattedDate, list);
}
}
}
// Sort the values inside the map based on dates
for (Entry<String, ArrayList<BookingDTO>> entry : mapObj.entrySet()) {
Collections.sort(entry.getValue(), new BookDTOComparator(DATES));
}
for (Entry<String, ArrayList<BookDTO>> entry : mapObj.entrySet()) {
serialNumber = setItinerarySerialNumber(entry.getValue(), serialNumber);
}
Upvotes: 0
Views: 70
Reputation: 358
Arrays.parallelSort(entry.getValue())
if lists are too large and it is applicableAlso, if it applicable, see code below:
int serialNumber = 1;
SimpleDateFormat format = new SimpleDateFormat("dd-MM-yyyy");
ArrayList<BookDTO> hListCopy = new ArrayList<>(hList);
Collections.sort(hListCopy, new NewBookDTOComparator()); // 2. sorting
HashMap<String, ArrayList<BookDTO>> mapObj = new HashMap<>();
for (BookDTO bookDTO : hListCopy) {
serialNumber = setItinerarySerialNumber(bookDTO, serialNumber); // 3. serialNumber
Calendar depDate = bookDTO.getDepartureDate();
if (depDate != null) {
String formattedDate = format.format(depDate.getTime());
if (mapObj.containsKey(formattedDate)) {
mapObj.get(formattedDate).add(bookDTO);
} else {
ArrayList<BookDTO> list = new ArrayList<>();
list.add(bookDTO);
mapObj.put(formattedDate, list);
}
}
}
So, only one loop (and one sorting algorithm).
For list cope-constructor used System.arraycopy
internally, you can google performance of.
NewBookDTOComparator
, you should sort not only by minutes and hours, but also by 'DepartureDate'SimpleDateFormat format
should be static field or class field.Arrays.parallelSort(hListCopy)
if lists are too large and it is applicableUpvotes: 1