现在遇到的排序场景是 根据集合对象中,优先按照A字段排序,A字段相等,则按照B字段排序,C字段不为空的放最后。
Collections.sort 排序的返回值 是 1 ,0 -1 其中,a.compareTo(b)==0,是 二者相等,a.compareTo(b)==1, 是 a大于b
public class Test01 {
public static void main(String[] args) {
List<FundBenchMarkInfo> fundBenchMarkList = new ArrayList<>();
fundBenchMarkList.add(new FundBenchMarkInfo("2",new BigDecimal("123"),null));
fundBenchMarkList.add(new FundBenchMarkInfo("5",new BigDecimal("12"),null));
fundBenchMarkList.add(new FundBenchMarkInfo("1",new BigDecimal("8"),null));
fundBenchMarkList.add(new FundBenchMarkInfo("7",new BigDecimal("8"),new BigDecimal("123345")));
fundBenchMarkList.add(new FundBenchMarkInfo("8",new BigDecimal("3"),new BigDecimal("90")));
fundBenchMarkList.add(new FundBenchMarkInfo("9",new BigDecimal("8"),null));
Collections.sort(fundBenchMarkList, new Comparator<FundBenchMarkInfo>() {
@Override
public int compare(FundBenchMarkInfo me1, FundBenchMarkInfo me2) {
int result = 0;
if (null != me1.getEnConstant()) {
return -1;
}
if (null != me2.getEnConstant()) {
return -1;
}
if (me1.getEnWeight().compareTo(me2.getEnWeight()) == result) {
result = me1.getIndexScod().compareTo(me2.getIndexScod());
} else {
result = me1.getEnWeight().compareTo(me2.getEnWeight());
}
return result;
}
});
System.out.println(JSON.toJSONString(fundBenchMarkList));
}
}
public class FundBenchMarkInfo {
private String indexScod;
private BigDecimal enWeight;
private BigDecimal enConstant;
public FundBenchMarkInfo() {
}
public FundBenchMarkInfo(String indexScod, BigDecimal enWeight, BigDecimal enConstant) {
this.indexScod = indexScod;
this.enWeight = enWeight;
this.enConstant = enConstant;
}
public String getIndexScod() {
return indexScod;
}
public void setIndexScod(String indexScod) {
this.indexScod = indexScod;
}
public BigDecimal getEnWeight() {
return enWeight;
}
public void setEnWeight(BigDecimal enWeight) {
this.enWeight = enWeight;
}
public BigDecimal getEnConstant() {
return enConstant;
}
public void setEnConstant(BigDecimal enConstant) {
this.enConstant = enConstant;
}
@Override
public String toString() {
return "FundBenchMarkInfo{" +
"indexScod='" + indexScod + '\'' +
", enWeight=" + enWeight +
", enConstant=" + enConstant +
'}';
}
}
|