3
\$\begingroup\$

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.

\$\endgroup\$

3 Answers 3

4
\$\begingroup\$

You can also chain the Comparators using thenComparing

CASE_INSENSITIVE_COMPARATOR = Comparator.comparing((Function<String, String>) String::toLowerCase)
                                        .thenComparing(o -> o);

Official Java docs on thenComparing.

\$\endgroup\$
3
\$\begingroup\$

I suggest a modification of @Ankint Soni solution with less structural diversity:

CASE_INSENSITIVE_COMPARATOR = Comparator.<String, String>comparing(o -> o.toLowerCase()).thenComparing(o -> o);

Or a slightly different flavor, more expressive:

CASE_INSENSITIVE_COMPARATOR = Comparator.<String, String>comparing(o -> o.toLowerCase()).thenComparing(Comparator.naturalOrder());
\$\endgroup\$
3
  • \$\begingroup\$ Second example: Do you mean more expensive in the performance? \$\endgroup\$ Commented Jul 26, 2018 at 10:50
  • \$\begingroup\$ The why do you show me this?)) \$\endgroup\$ Commented Jul 26, 2018 at 11:01
  • \$\begingroup\$ If you have performance problems at this point you have a general performance problem. \$\endgroup\$
    – oopexpert
    Commented Jul 26, 2018 at 14:03
2
\$\begingroup\$

Even in the lambda, the RHS can be a code block with braces.

private static final Comparator<String> CASE_INSENSITIVE_COMPARATOR_LAMBDA = 
(s1, s2) -> {
    int cmp = o1.toLowerCase().compareTo(o2.toLowerCase());
    if (cmp != 0) return cmp;

    return o1.compareTo(o2);
};
\$\endgroup\$
2
  • \$\begingroup\$ Thanks for the hint. What is a RHS? \$\endgroup\$ Commented Jul 25, 2018 at 14:56
  • \$\begingroup\$ Right hand side :) \$\endgroup\$
    – Teddy
    Commented Jul 25, 2018 at 14:58

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.