I am writing a Comparator for my TreeMap. It looks like this:
private static final Comparator<String> CASE_INSENSITIVE_COMPARATOR =
new Comparator<String>() {
@Override
public int compare(String o1, String o2) {
int cmp = o1.toLowerCase().compareTo(o2.toLowerCase());
if (cmp != 0) return cmp;
return o1.compareTo(o2);
}
};
My IDE hints me that it could be written in a lambda. I came up with this idea:
private static final Comparator<String> CASE_INSENSITIVE_COMPARATOR_LAMBDA =
(s1, s2) ->
s1.toLowerCase().compareTo(s2.toLowerCase()) == 0 ?
s1.compareTo(s2) : s1.toLowerCase().compareTo(s2.toLowerCase());
But then I am duplicating the first call s1.toLowerCase().compareTo(s2.toLowerCase()
. This is doing two String manipulation and one comparison more than the not lambda expression.