Assume that I have a data input like this:
018492114,51863406,X0,1,20160218
018529816,51864472,X0,1,20150603
018543434,51864629,X0,1,20150702
018543464,51864990,N5+,1,2015063
018530309,51865142,X0,1,20150603
I want only to convert the 5 column's element to Date format because it was imported as a string. And I want to do a sorting operation by DA_PRM_CTR_ORDER variable (the end column).
Note that I am using arraylist object defined as Personne and I am using Comparable interface to use Comparable method for sorting:
this is my class personne which includes the needed object:
public class Personne implements Comparable {
private String IDC_PSE_PCL;
private String IDC_CD_NOT;
private String CD_NOTE;
private String IDT_ETT_PSE;
private String DA_PRM_CTR_ORDER;
public Personne(String IDC_PSE_PCL, String IDC_CD_NOT,
String DA_PRM_CTR_ORDER, String IDT_ETT_PSE, String CD_NOTE) {
this.IDC_PSE_PCL = IDC_PSE_PCL;
this.IDC_CD_NOT = IDC_CD_NOT;
this.IDT_ETT_PSE = IDT_ETT_PSE;
this.CD_NOTE = CD_NOTE;
this.DA_PRM_CTR_ORDER = DA_PRM_CTR_ORDER;
}
public String getIDC_CD_NOT() {
return this.IDC_CD_NOT;
}
public String getIDC_PSE_PCL() {
return this.IDC_PSE_PCL;
}
public String getDA_PRM_CTR_ORDER() {
return this.DA_PRM_CTR_ORDER;
}
public String getIDT_ETT_PSE() {
return this.IDT_ETT_PSE;
}
public String getCD_NOTE() {
return this.CD_NOTE;
}
@Override
public int compareTo(Object o) {
Personne other = (Personne) o;
DateFormat df = new SimpleDateFormat("yyyyMMdd");
Date converted = (Date) df.parse(other.getDA_PRM_CTR_ORDER());
int res = this.DA_PRM_CTR_ORDER.compareTo(converted);
// Si Egalite des dates
if (res == 0) {
res = IDT_ETT_PSE.compareTo(other.getIDT_ETT_PSE());
}
return res;
}
My problem is in the line:
int res = this.DA_PRM_CTR_ORDER.compareTo(converted);
when I want to sort by DA_PRM_CTR_ORDER values but it show me this problem:
The method compareTo(String) in the type String is not applicable for the arguments (Date)
How can I resolve this issue please?
other.getIDT_ETT_PSE()does not convert theStringto aDate, does it? I recommend using suitable data types instead ofString. If an attributes represents a date, usejava.time.LocalDate, you can directly compare it since it implementsComparable.DateFormat,SimpleDateFormatandDate. Those classes are poorly designed and long outdated, the first two in particular notoriously troublesome. Instead useLocalDateandDateTimeFormatter.BASIC_ISO_DATE, both from java.time, the modern Java date and time API.