TheByeByeMan
TheByeByeMan

Reputation: 1424

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 ?

Upvotes: 0

Views: 242

Answers (2)

sinujohn
sinujohn

Reputation: 2604

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()));

Upvotes: 1

Norbert Radyk
Norbert Radyk

Reputation: 2618

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());
}  

Upvotes: 4

Related Questions