简体   繁体   English

对象排序列表

[英]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. 我想在其中按字母顺序对字符串字段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. 您需要实现compare方法。

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: 在Java世界中,通常我们使用匿名内部类按以下方式内联:

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'. 因此,您的比较器需要做的是针对给定的一对WorkFlowErrors(首先)进行决策。

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. 如果您始终希望以这种方式比较WorkflowError对象,最简单的方法是在WorkflowError本身上实现Comparable<WorkflowError>

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

That's assuming errorCode implements Comparable. 假设errorCode实现了Comparable。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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