Reputation: 16050
I need to sort elements based on time windows, e.g.
8:00 - 9:00
8:00 - 11:00
9:00 - 10.00
9:00 - 12:00
So far my idea is to sort open times and close times as separate Maps
, and then try to create the final List
sortedList
. I'm not sure however that this idea is the most efficient solution. Is there any way to solve this issue in the easier way?
private List<Customer> sortCustomersByTimeWindows(List<Customer> _C)
{
List<Customer> sortedList = new ArrayList<Customer>();
Map<Integer,Integer> openTimes = new HashMap<Integer,Integer>();
Map<Integer,Integer> closeTimes = new HashMap<Integer,Integer>();
for (int i=0; i<_C.size(); i++)
{
openTimes.put(i,_C.get(i).getOpenTime());
closeTimes.put(i,_C.get(i).getCloseTime());
}
List<Integer> openTimes_values = new ArrayList<Integer>(openTimes.values());
List<Integer> closeTimes_values = new ArrayList<Integer>(closeTimes.values());
Collections.sort(openTimes_values, new Comparator<Integer>() {
public int compare(Integer o1, Integer o2) {
return o1 - o2;
}
});
Collections.sort(closeTimes_values, new Comparator<Integer>() {
public int compare(Integer o1, Integer o2) {
return o1 - o2;
}
});
for (int i=0; i<_C.size(); i++)
{
//...
}
return sortedList;
}
Upvotes: 0
Views: 83
Reputation: 1756
You could have a map of Integer, Integer that maps from the opening time to the closing time Then you can sort by keys or by values
Collections.sort(_C, new Comparator<Customer>() {
public int compare(Customer o1, Customer o2) {
return //the test case here for times or whatever you need
}
});
Upvotes: 1
Reputation: 20628
Just use a custom comparator that sorts your customers based on the times:
Collections.sort(_C, new Comparator<Customer>() {
@Override
public int compare(Customer c1, Customer c2) {
int openTimeDiff = c1.getOpenTime() - c2.getOpenTime();
if (openTimeDiff != 0)
return openTimeDiff;
return c1.getCloseTime() - c2.getCloseTime();
}
});
Upvotes: 3