Re: verbose sort
Eric Sosman wrote:
To: bob smith
From: Eric Sosman <esosman@ieee-dot-org.invalid>
On 8/2/2012 11:37 AM, bob smith wrote:
I have some code that sorts a list like so:
Vector<String> my_list = new Vector<String>();
Comparator<String> c = new Comparator<String>() {
@Override
public int compare(String object1, String object2) {
if (object1 == null)
return -1;
if (object2 == null)
return 1;
object1 = object1.toLowerCase();
object2 = object2.toLowerCase();
return object1.compareTo(object2);
};
};
Collections.sort(my_list, c);
This seems like a lot of code for such a common operation. Is there a more
succinct way of doing this?
Consider using compareToIgnoreCase(). Also, think about what
happens when two null's are compared: You should return zero rather than
declaring one of them "less than" the other, because otherwise your comparator
is inconsistent (you can have A<B, B<C, but C<A).
public int compare(String s1, String s2) {
if (s1 == null)
return s2 == null ? 0 : -1;
return s2 == null ? +1 : s1.compareToIgnoreCase(s2);
}
I'd do it as a fastpath and GoF Decorator
public final class NullFirstComparator<T> implements Comparator<T> {
@NonNull
private final Comparator<T> delegate;
public NullFirstComparator(@NonNull final Comparator<T> delegate) {
this.delegate = delegate;
}
public int compare(final T t1, final T t2) {
if (t1 == t2) {
return 0;
} else if (t1 == null) {
return -1;
} else if (t2 == null) {
return 1;
} else {
return delegate.compare(t1, t2);
}
}
}
Collections.sort(my_list, new NullFirstComparator<String>(String.CASE_INSENSITIVE_ORDER));
--
"I'm a doctor, not a mechanic." Dr Leonard McCoy <mccoy@ncc1701.starfleet.fed>
"I'm a mechanic, not a doctor." Volker Borchert <v_borchert@despammed.com>