下面是我为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;
}
}
答案 0 :(得分:0)
你可以像这样简化:
int status = o1.getStatusInd().toLowerCase().compareTo(o2.getStatusInd().toLowerCase());
if (status == 0)
status = o1.getOfferPgm().toLowerCase().compareTo(o2.getOfferPgm().toLowerCase());
return status;
如果getStatusInd
或getOfferPgm
可以返回null,则需要稍微修改此代码以避免NPE