简体   繁体   English

使用Java中的可比较按两个字段升序和降序对对象列表进行排序

[英]Sort a list of objects by two fields ascending order and descending order using comparable in Java

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我已经找到了一些关于使用多个字段对对象列表进行排序的结果,但我不明白如何使用可比较的两个字段升序和降序对列表进行排序这是我的代码,我想按降序对列表进行排序(datejournal) 然后按升序为 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());
        }
    }
}

You can compare first DateJournal(in descending order) and after that CodeJournal(in ascending order) as given below:您可以比较第一个 DateJournal(按降序)和之后的 CodeJournal(按升序),如下所示:

@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;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM