简体   繁体   English

限制方法引用参数类型

[英]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.这不起作用,因为premiumStrings::contains可以接受任何对象而不仅仅是字符串。 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?可以将其替换为(String s) -> premiumStrings.contains(s) ,但是有没有办法在仍然使用方法引用 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>>>) .) (具体来说,问题是The method thenComparing(Comparator<? super Object>) in the type Comparator<Object> is not applicable for the arguments (Comparator<Comparable<? super Comparable<? super T>>>) 。)

Help the compiler a bit with types:帮助编译器使用类型:

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

The compiler should infer the types of arguments passed to each method.编译器应该推断传递给每个方法的参数类型。

And when we have a chain of methods, the context doesn't provide enough information for that.当我们有一个方法链时,上下文并没有为此提供足够的信息。 And the argument of every method reference (or lambda expression) would be treated as being of type Object and not String .并且每个方法引用(或 lambda 表达式)的参数都将被视为Object而不是String类型。

To avoid that, we can provide the type explicitly as a parameter of a lambda expression:为避免这种情况,我们可以显式提供类型作为 lambda 表达式的参数:

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

Or by using so-called Type Witness : Comparator.<String>comparing().thenComparing() .或者通过使用所谓的Type WitnessComparator.<String>comparing().thenComparing()

For more information, see .有关详细信息, 请参阅

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM