javalambdamethod-reference

Restrict method reference parameter type


Set<String> premiumStrings = new HashSet<>();
Set<String> sortedSet = new TreeSet<>(Comparator.comparing(premiumStrings::contains).thenComparing(Comparator.naturalOrder()));

This doesn't work, because premiumStrings::contains can take any object and not just strings. One can replace it with (String s) -> premiumStrings.contains(s), but is there a way to restrict the parameter type while still using a method reference lambda?

(Specifically, the problem is The method thenComparing(Comparator<? super Object>) in the type Comparator<Object> is not applicable for the arguments (Comparator<Comparable<? super Comparable<? super T>>>).)


Solution

  • Help the compiler a bit with types:

    Set<String> sortedSet = new TreeSet<>(
                    Comparator.<String, Boolean>comparing(premiumStrings::contains).thenComparing(Comparator.naturalOrder()));