Java比较器逻辑。建议更好的写作方式

时间:2016-03-11 22:27:00

标签: java comparator

下面是我为CustomComparator编写的一段逻辑,但对它不是很满意。任何人都可以就我如何改进它给我一些建议。

public class CustomComparator implements Comparator<Offer>, Serializable {

private static final long serialVersionUID = 8040322980719271561L;

@Override
public int compare(final Offer o1, final Offer o2) {

    int comparisonIndicator = 0;

    if (("B".equals(o1.getStatusInd()))
        && (!("B".equals(o2.getStatusInd())))) {
        comparisonIndicator = -1;
    }
    else if (("B".equals(o2.getStatusInd()))
        && (!("B".equals(o1.getStatusInd())))) {
        comparisonIndicator = 1;
    }
    else if (("PD".equalsIgnoreCase(o1.getOfferPgm()))
        && (!"PD".equalsIgnoreCase(o2.getOfferPgm()))) {
        comparisonIndicator = -1;
    }
    else if (("PD".equalsIgnoreCase(o2.getOfferPgm()))
        && (!"PD".equalsIgnoreCase(o1.getOfferPgm()))) {
        comparisonIndicator = -1;
    }
    return comparisonIndicator;
}

}

1 个答案:

答案 0 :(得分:0)

你可以像这样简化:

int status = o1.getStatusInd().toLowerCase().compareTo(o2.getStatusInd().toLowerCase());
if (status == 0)
    status = o1.getOfferPgm().toLowerCase().compareTo(o2.getOfferPgm().toLowerCase());
return status;

如果getStatusIndgetOfferPgm可以返回null,则需要稍微修改此代码以避免NPE