For objects a and b implementing the Comparable interface I want to avoid having code like
if (a.compareTo(b) > 0) {
...
}
instead, I am looking for helper methods like
if (a.isGreaterThan(b)) {
...
}
This would help me a lot for not always having to look up the definition of the return value of compareTo(T o):
Returns a negative integer, zero, or a positive integer as this object is less than, equal to, or greater than the specified object.
Really helpful would be 5 different methods:
Instead of use potential helper method:
a.compareTo(b) < 0 a.isLessThan(b)
a.compareTo(b) <= 0 a.isLessOrEqualTo(b)
a.compareTo(b) == 0 a.isEqualTo(b)
a.compareTo(b) >= 0 a.isGreaterOrEqualTo(b)
a.compareTo(b) > 0 a.isGreaterThan(b)
Are there any helper methods like this in the JDK or other libraries that provide this kind of functionality?
You do not need these methods if you'll remember, that it's just enough to have a mental substitution by carrying the compareTo argument to the right side of comparison as following:
a.compareTo(b) < 0 ----> a[.compareTo(...)] < b
Since it's that simple, noone usually cares about having any better form of comparison in a library. If you still insist on some more readable form of expression, you can use default methods from Java 8 to extend Comparable interface as following:
public interface ComparableDSL<T> extends Comparable<T> {
default boolean isLessThan(T that) {
return compareTo(that) < 0;
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With