简体   繁体   中英

Sorting a List of Objects by specific value

I want to sort a List of Objects (Remarks) by a value contained in another object (DefectClass).

public class Remark {
private int remarkId;
private DefectClass defectClass;
}

I have a List of Remarks and I'm using this code to sort them by the title of the defectClass :

Collections.sort(remarks, new Comparator<Remark>()
            {
                @Override
                public int compare(Remark arg0, Remark arg1) {
                return arg0.getDefectClass().compareTo(arg1.getDefectClass());
                }
            });

and this is the Compare to methode in my DefectClass model :

public class DefectClass implements Comparable<DefectClass> {
private String DefectClassTitle;
/* Getters And Setters */
    @Override
public int compareTo(DefectClass o) {
    if(o.getDefectClassTitle().equals(this.getDefectClassTitle()))
        return 0;
    else
        return 1;
}

by these codes I want to sort a List of remarks by the Title of the DefectClass of these Remarks ... but At the end I always get the same list with no sorting. What I'm doing wrong ?

The implementation of the DefectClass.compareTo() method is incorrect, as it should compare the 2 objects and return whether the first one is lower (-1), equal(0) or greater (1) to the second one (and not only indicate whether they're equal as in your case). Assuming getDefectClassTitle() is returning String I'd implement the method as:

public int compareTo(DefectClass o) {
    return o.getDefectClassTitle().compareTo(this.getDefectClassTitle());
}  

You need not even implement Comparable , as you are providing your own Comparator .
Use it as follows:

Collections.sort(remarks, (r1, r2) -> r1.getDefectClass().getDefectClassTitle().compareTo(r2.getDefectClass().getDefectClassTitle()));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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