0

I have a list of objects:

List<WorkflowError> workflowErrors = new List<WorkflowError>();

Of which I am wanting to sort alphabetically on the string field errorCode.

I know I have to use

Collections.sort(list,comparator) 

and write a custom Comparator:

public class SortByErrorComparator implements Comparator<WorkflowError>
{
    // Comparator logic    
    return 0;
}

I have seen examples of how to do this for a one dimensional list but I can't work out how to begin for a list of objects.

Any help would be appreciated.

1
  • Where is the // comparator logic? Commented Feb 13, 2012 at 12:01

4 Answers 4

9

You need to implement the compare method.

public class SortByErrorComparator implements Comparator<WorkflowError> {
    public int compare(WorkflowError obj1, WorkflowError obj2) {
        return obj1.getErrorCode().compareTo(obj2.getErrorCode());
    }
}

And then, you can simply do:

Collections.sort(list, new SortByErrorComparator()) ;

In the Java world, generally we do it inline using anonymous inner classes as so:

Collections.sort(list, new Comparator<WorkflowError>() {
    public int compare(WorkflowError obj1, WorkflowError obj2) {
        return obj1.getErrorCode().compareTo(obj2.getErrorCode());
    }
});
Sign up to request clarification or add additional context in comments.

1 Comment

Works perfectly, I didn't know how the compareTo() would behave for strings actually. Thanks a lot.
0

In your comparator, you have to explain how the specific object should be sorted.

if (obj.att1 < obj2.att2)
   ...

do you get it?

Comments

0

When sorting the list the sort implementation will use your comparator to compare individual paisr of objects. So what your comparator needs to do is decide, for a given pair of WorkFlowErrors, which comes 'first'.

from what you've said this sounds like just getting the error code from each one and doing a string compairson.

Comments

0

If you will always want to compare WorkflowError objects in this manner, the easiest way is to implement Comparable<WorkflowError> on WorkflowError itself.

public int compareTo(WorkflowError that) {
    return this.getErrorCode().compareTo(that.getErrorCode());
}

That's assuming errorCode implements Comparable.

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.