具有多个字段的对象的Java Comparator [英] Java Comparator for Objects with multiple fields

查看:241
本文介绍了具有多个字段的对象的Java Comparator的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个包含5个字段的对象集合

I have an Object Collection with 5 fields:

id;
entityType;
entityId;
brandId;
productId;

排序 ArrayList Collection 我写了以下 Comparaor

Comparator<Collection> collectionComparator = new Comparator<Collection>() {

    @Override
    public int compare(Collection collection1, Collection collection2) {
        if(collection1.getId().equals(collection2.getId())) {
            if(collection1.getEntityType().equals(collection2.getEntityType())) {
                if(collection1.getEntityId().equals(collection2.getEntityId())) {
                    if(collection1.getBrandId().equals(collection2.getBrandId())) {
                        return collection1.getProductId().compareTo(collection2.getProductId());
                    } else {
                        return collection1.getBrandId().compareTo(collection2.getBrandId());
                    }
                } else {
                    return collection1.getEntityId().compareTo(collection2.getEntityId());
                }
            } else {
                return collection1.getEntityType().compareTo(collection2.getEntityType());
            }
        } 

        return collection1.getId().compareTo(collection2.getId());
    }
};

这是实施 Comparator的正确方法在具有多个要比较的字段的对象上?

Is this the right way to implement Comparator on the object which has multiple fields to compare?

推荐答案

您的方法可能正确,但效率低(不必要地调用equals)而且难以阅读。它可以改写如下:

Your method might be correct, but it is inefficient (unnecessarily calls equals) and difficult to read. It could be rewritten something like this:

public int compare(Collection c1, Collection c2)
{
    int n;
    n = c1.id.compareTo(c2.id);
    if (n != 0) return n;
    n = c1.entityType.compareTo(c2.entityType);
    if (n != 0) return n;
    n = c1.brandId.compareTo(c2.brandId);
    if (n != 0) return n;
    return c1.productId.compareTo(c2.productId);
}

更好的方法是使用一种库方法,将所有这些逻辑抽象出去,这样你就可以了不必考虑它。例如。使用 apache.commons.lang CompareToBuilder

Even better is to use a library method which abstracts all this logic away so you don't have to think about it. E.g. using apache.commons.lang CompareToBuilder

public int compare(Collection c1, Collection c2)
{
    return new CompareToBuilder()
            .append(c1.id, c2.id)
            .append(c1.entityType, c2.entityType)
            .append(c1.brandId, c2.brandId)
            .append(c1.productId, c2.productId)
            .toComparison();
}

这篇关于具有多个字段的对象的Java Comparator的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆