I know similar questions have been asked before but I have a specific problem which I can't get my head wrong.
I want to sort a map by days of the week where days of the week are keys of the map. How do you compare strings which don't have natural order in compare method? Map at the end of the sort should be: Mon, Tue, Wed, Thur.
Here is my code so far but I am stuck at compare method.
class OpeningTimes {
private String openingTime;
private String closingTime;
public String getOpeningTime() {
return openingTime;
}
public void setOpeningTime(String openingTime) {
this.openingTime = openingTime;
}
public String getClosingTime() {
return closingTime;
}
public void setClosingTime(String closingTime) {
this.closingTime = closingTime;
}
@Override
public String toString() {
return new StringBuilder( "Opening Times: " + this.openingTime + " Closing Times: " + this.closingTime).toString();
}
}
Comparator:
class OpeningTimesComparator implements Comparator<Map.Entry<String, OpeningTimes>>{
@Override
public int compare(Entry<String, OpeningTimes> o1, Entry<String, OpeningTimes> o2) {
return 0; // what is the logic?
}}
Runner:
public class TestClass {
public static void main(String[] args) {
Map<String, OpeningTimes> openingTimesMap = new TreeMap<String, OpeningTimes>();
OpeningTimes openTime1 = new OpeningTimes();
openTime1.setOpeningTime("9PM");
openTime1.setClosingTime("10PM");
OpeningTimes openTime2 = new OpeningTimes();
openTime2.setOpeningTime("11PM");
openTime2.setClosingTime("9PM");
OpeningTimes openTime3 = new OpeningTimes();
openTime3.setOpeningTime("13PM");
openTime3.setClosingTime("14PM");
OpeningTimes openTime4 = new OpeningTimes();
openTime4.setOpeningTime("15PM");
openTime4.setClosingTime("13PM");
openingTimesMap.put("Tue", openTime2);
openingTimesMap.put("Thu", openTime4);
openingTimesMap.put("Mon", openTime1);
openingTimesMap.put("Wed", openTime3);
for (Entry<String, OpeningTimes> openingTimesSingle : openingTimesMap.entrySet()) {
System.out.println("Key: " + openingTimesSingle.getKey() + " Value: " + openingTimesMap.get(openingTimesSingle.getKey()));
}
List<Map.Entry<String, OpeningTimes>> list = new ArrayList<Map.Entry<String, OpeningTimes>>(openingTimesMap.entrySet());
Collections.sort(list, new OpeningTimesComparator());
for (Entry<String, OpeningTimes> openingTimesSingle : openingTimesMap.entrySet()) {
System.out.println("Key: " + openingTimesSingle.getKey() + " Value: " + openingTimesMap.get(openingTimesSingle.getKey()));
}
}
}
Thanks in advance