user782104
user782104

Reputation: 13555

Sort an arraylist of custom object in android

There is an object like this:

dataObj
=============
name
address
isTopPriority

So I have an arrayList of dataObj, how to sort the dataObj to "if isTopPriority is true, then they will be the fronter part of the array" ? Thanks

Attempt the code like:

private class CustomComparator implements Comparator<Spot> {
        @Override
        public int compare(Spot lhs, Spot rhs) {
            // TODO Auto-generated method stub
            return lhs.isStar.compareTo();
        }
    }

But I am confused about why to compare between 2 object , I would like to comapre like this:

just if (currentObj.isFirstPriority == true) then return the object.

Thanks for helping

Upvotes: 0

Views: 777

Answers (2)

Autocrab
Autocrab

Reputation: 3787

This will sort primary by priority, and secondary by name.

private static final Comparator<Data> dataComparator = new Comparator<Data>() {
    @Override
    public int compare(Data o1, Data o2) {
        if (o1.isTopPriority() && o2.isTopPriority())
            return o1.getName().compareTo(o2.getName());
        if (o1.isTopPriority())
            return 1;
        if (o2.isTopPriority())
            return -1;
        return o1.getName().compareTo(o2.getName());
    }
};

Upvotes: 1

ddmps
ddmps

Reputation: 4390

A Comparator "has" to return -1 if rhs is "more" than lhs, 0 if they're equal and 1 if it's less. This is so the sorting is actually consistent (if you sort rhs comparing it to lhs and lhs comparing it to rhs it has to have the opposite result, or 0). The following Comparator does that:

private class CustomComparator implements Comparator<Spot> {
    @Override
    public int compare(Spot lhs, Spot rhs) {
        if (lhs.isStar == rhs.isStar) return 0;
        else if (lhs.isStar) return 1;
        return -1;
    }
}

You also have to actually sort it, but I'm guessing you know how to do that (Collections.sort(arrayList, comparator)).

Upvotes: 1

Related Questions