-1

I already found some result about sorting list of object using multiple fields, but i didn't understand how can i sort a list by two fields ascending order and descending order using comparable Here is my code, i want to sort the list by descending order (datejournal) then by ascending order for codejournal

public class journal implements Comparable<journal>{
    private String codeJournal;
    private String dateLivraison;
    private int qteJournal;

    public String getCodeJournal() {
        return codeJournal;
    }
    public void setCodeJournal(String codeJournal) {
        this.codeJournal = codeJournal;
    }
    public String getDateLivraison() {
        return dateLivraison;
    }
    public void setDateLivraison(String dateLivraison) {
        this.dateLivraison = dateLivraison;
    }
    public int getQteJournal() {
        return qteJournal;
    }
    public void setQteJournal(int qteJournal) {
        this.qteJournal = qteJournal;
    }
    @Override
    public String toString() {
        return "journal [codeJournal=" + codeJournal + ", dateLivraison=" + dateLivraison + ", qteJournal=" + qteJournal
                + "]";
    }
    @Override
    public int compareTo(journal arg0) {
        if(this.dateLivraison.equals(arg0.getDateLivraison())){
            return -this.dateLivraison.compareTo(arg0.getDateLivraison());
        }
    }
}
Erwin Smith
  • 65
  • 2
  • 11
  • Why are you using `Comparable`? Use `Comparator` instead. Also which fields are you talking about to be sorted in ascending and descending order? – Nicholas K Jan 01 '19 at 16:21
  • Providing a concrete input/output example is always a good idea to illustrate exactly what your goal is. In your `compareTo` function, you never use `codeJournal`. If two of your primary sort keys are equal, then you can consider your secondary key and sort it in whichever direction you wish (ascending or descending). Otherwise, just sort by the primary sort key in whichever direction you wish. – ggorlen Jan 01 '19 at 16:31
  • Side note: Class names should start in uppercase to avoid confusions with variable names, which start in lowercase. – Progman Jan 01 '19 at 16:36
  • Possible duplicate of [Using Comparable for multiple dynamic fields of VO in java](https://stackoverflow.com/questions/16206629/using-comparable-for-multiple-dynamic-fields-of-vo-in-java) – Nicholas K Jan 01 '19 at 16:39

1 Answers1

1

You can compare first DateJournal(in descending order) and after that CodeJournal(in ascending order) as given below:

@Override
public int compare(final journal j1, final journal j2) {
    int res;
    res = j2.getDateLivraison().compareTo(j1.getDateLivraison());
    if (res == 0)
        res = j1.getCodeJournal().compareTo(j2.getCodeJournal());
    return res;
}
mukesh210
  • 2,792
  • 2
  • 19
  • 41