kondal
kondal

Reputation: 358

Sort List objects based on object data type

I have List of LabResults objects, i wanted to sort based on list object data,here is my collection

public class LabResult implements Serializable{

private String id;
private String name;
private String unit;
private String abnormal;  //Contains String either "A" or "N"

}
private List<LabResult> mLabResults;

I want to sort the list to show abnormal = "A" on top of list view and rest under that can any one suggest me how to do that in java/android

Upvotes: 1

Views: 196

Answers (1)

Blackbelt
Blackbelt

Reputation: 157447

Use a comparator

public class LabResultComparator implements Comparator<LabResult> {
    public int compare(LabResult p1, LabResult p2) {
        return p1.abnormal.compareTo(p2.abnormal);
    }
}

compareTo retuns 0 if the two strings are equal, a value less than 0 if p1.abnormal is greater than p2.abnormal, and the other way around.

Upvotes: 5

Related Questions