Implement Comparator for primitive boolean type?
Since Java 7, the logic that Marko Topolnik showed in his answer has moved into another method to expose a way to compare primitive boolean
.
Javadoc for Boolean.compare(boolean x, boolean y)
:
public static int compare(boolean x, boolean y)
Compares two boolean values. The value returned is identical to
what would be returned by:
Boolean.valueOf(x).compareTo(Boolean.valueOf(y))
You can look up how it is implemented for the java.lang.Boolean
, since that class, naturally, uses a primitive boolean as well:
public int compareTo(Boolean b) {
return (b.value == value ? 0 : (value ? 1 : -1));
}
As of Java 7 you can simply use the built-in static method Boolean.compare(a, b)
.
An even better approach and correct use of Boolean-Adapter class
public int compare(boolean lhs, boolean rhs) {
return Boolean.compare(lhs, rhs);
}
EDIT:
Hint: This sorts the "false" values first. If you want to invert the sorting use:
(-1 * Boolean.compare(lhs, rhs))