Reputation: 10695
I have a Meeting
class that implements Comparable<Meeting>
. Overridden compareTo
method will compare meetingDate
of two Meeting
objects first and in case they are equal it will compare their meetingTime
. I want to put all my Meeting
objects in a ProirtiyQueue<Meeting>
so I can retrieve the upcoming meetings as per their meetingDate
and meetingTime
. Data type used are java.time.LocalDate and java.time.LocalTime respectively. How can I compare meetingDate
and meetingTime
in my compareTo(Meeting o)
method.
public class Meeting implements Comparable<Meeting> {
private String title;
private String desciption;
private LocalDate meetingDate;
private LocalTime meetingTime;
public Meeting(String title, String description, LocalDate meetingDate, LocalTime meetingTime) {
this.title = title;
this.desciption = description;
this.meetingDate = meetingDate;
this.meetingTime = meetingTime;
}
public String getTittle() {
return title;
}
public void setTittle(String title) {
this.title = title;
}
public String getDescription() {
return desciption;
}
public void setDescription(String description) {
this.desciption = description;
}
public LocalDate getMeetingDate() {
return meetingDate;
}
public void setMeetingDate(LocalDate meetingDate) {
this.meetingDate = meetingDate;
}
public LocalTime getMeetingTime() {
return meetingTime;
}
public void setMeetingTime(LocalTime meetingTime) {
this.meetingTime = meetingTime;
}
public int compareTo(Meeting o) {
// comparison
}
}
Upvotes: 1
Views: 2563
Reputation: 14257
You can delegate the implementation of compareTo
to a Comparator
which can chain comparisons of multiple properties of the given Meeting:
public class Meeting {
...
private static final Comparator<Meeting> comparator =
Comparator.comparing(Meeting::getMeetingDate)
.thenComparing(Meeting::getMeetingTime);
@Override
public int compareTo(Meeting that) {
comparator.compare(this, that);
}
Upvotes: 2
Reputation: 5287
As per the documentation,
Date.compareTo()
Return : an int < 0 if this Date is less than the specified Date, 0 if they are equal, and an int > 0 if this Date is greater.
Time.before()
true if this time is less than the given time
Then you need something like :
public int compareTo(Meeting o) {
if (o == null)
return (0);
if (o.meetingDate.compareTo(meetingDate) == 0)
return (o.meetingTime.before(meetingTime));
else
return (o.meetingDate.compareTo(meetingDate));
}
This function will return : "An int < 0" if o is before the currentMeeting object. "An int > 0" if o is after the currentMeeting object.
Upvotes: 1