0

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

1

2 Answers 2

1

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)).

Sign up to request clarification or add additional context in comments.

1 Comment

the problem is it seems the sort is reverse, that means the star item is lower prioirty
1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.