Reputation: 517
I have a java People object :
public class People {
String lastname;
String firstname;
String gender;
String datebirth;
String fcolor;
public People(String lastname, String firstname, String gender,String datebirth, String fcolor) {
this.lastname = lastname;
this.firstname = firstname;
this.gender = gender;
this.datebirth = datebirth;
this.fcolor = fcolor;
}
public String getLastname() {
return lastname;
}
public String getFirstname() {
return firstname;
}
public String getGender() {
return gender;
}
public String getFcolor() {
return fcolor;
}
public String getDatebirth() {
return datebirth;
}
}
I want to create a Comparator to compare by datebirth (datebirth is sometimes in this format "2/13/1943", sometimes in this format "2-13-1943", can you help me on how to implement it.
I started this , but got confused :
import java.util.Date;
import java.text.SimpleDateFormat;
import java.util.Comparator;
import java.text.DateFormat;
public class CompareDateBirth implements Comparator<People>{
public int compare(People p, People q) {
DateFormat df = new SimpleDateFormat("dd-MM-yyyy");
Date Pdate = null;
Date Qdate= null;
try {
Pdate = df.parse(p.getDatebirth());
Qdate = df.parse(q.getDatebirth());
} catch (Exception e) {
e.printStackTrace();
}
return Pdate.compareTo(Qdate) > 0 ? 1 : 0;
}
}
Upvotes: 4
Views: 43207
Reputation: 787
You can use lambdas and out-of-the-box comparators since java 8, like this:
java.util.Comparator.comparing(Person::getBirthDate)
Upvotes: 1
Reputation: 308743
If you'd store birth date using its proper type - a java.util.Date
object instead of a String
- you wouldn't have this problem. Formatting is a display issue.
A class named "People"?
Here's how I might do it (all classes below in separate .java files in a package named model):
package model;
public enum Gender { MALE, FEMALE }
public class Person {
private String firstName;
private String lastName;
private Gender gender;
private Date birthDate; // I'd make sure to set hh:mm:ss all to midnight
// constructors, getters, equals, hashCode, and toString are left for you
}
public class BirthDateComparator implements Comparator<Person> {
public int compare(Person p, Person q) {
if (p.getBirthDate().before(q.getBirthDate()) {
return -1;
} else if (p.getBirthDate().after(q.getBirthDate()) {
return 1;
} else {
return 0;
}
}
}
Upvotes: 13
Reputation: 21
Public class BirthDateComparator implements java.util.Comparator<Person> {
public int compare(Person p1, Person p2) {
return p1.getBirthDate().compareTo(p2.getBirthDate());
}
}
Upvotes: 1
Reputation: 1238
I suggest saving the date in your java code as a long that has the UNIX time of that date, it is more dependable across platforms. Also you could manually split the date using a delimiter, so if there is a '-' then that is your delimiter, else if there exists '/' then you split using that instead.
That way you can extract the day, month and year and construct the date object.
Upvotes: 1