我有以下代码,其中包含 2 个类 MyRange 和 MyCustomValue -
class MyRange {
private Long id;
private Double minValue;
private Double maxValue;
// getters and setters
// equals, hashCode and toString
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null || getClass() != obj.getClass())
return false;
MyRange other = (MyRange) obj;
return Objects.equals(this.id, other.id) &&
Objects.equals(this.minValue, other.minValue) &&
Objects.equals(this.maxValue, other.maxValue);
}
}
class MyCustomValue {
private String value;
private MyRange myrange;
//getters and setters
// equals, hashCode and toString
}
如果它value是空的,MyCustomValue我希望它在最后。所以我写了如下的比较器
public static final Comparator<MyCustomValue> externalMVComparator = (emv1, emv2) -> {
if(emv1.getValue() != null && emv2.getValue() == null) {
return -1;
} else if (emv1.getValue() == null && emv2.getValue() != null) {
return 1;
} else {
return myrangeMinValueComparator.compare(emv1, emv2);
}
}
private static final Comparator<MyRange> minValueComparator = Comparator.nullsLast(Comparator.comparingDouble(value -> value.getMinValue()));
private static final Comparator<MyCustomValue> myrangeMinValueComparator = Comparator.nullsLast(Comparator.comparing(MyCustomValue::getMyrange, minValueComparator));
上述比较器工作正常。所以我决定改变externalMVComparator如下(即,使用thenComparing更多的可读性)
private static final Comparator<MyCustomValue> valueComparator = Comparator.nullsLast(Comparator.comparing(MyCustomValue::getValue));
public static final Comparator<MyCustomValue> externalMVComparator2 = Comparator.nullsLast(valueComparator.thenComparing(myrangeMinValueComparator));
但是对列表进行排序,externalMVComparator2结果为NullPointerException. 我的代码中有什么错误?
白衣非少年
相关分类