简体   繁体   中英

Sorting list of objects

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.

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

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

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

do you get it?

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM