【发布时间】:2015-05-20 06:35:58
【问题描述】:
我正试图为here 所指出的问题编写一个解决方案,正如 Stuart Marks 指出的那样,它需要使用一个辅助类。由于这个错误,我卡在了代码上:
Test.java:27: error: incompatible types: inference variable K has incompatible bounds
.collect(Collectors.groupingBy(p -> p.getT2()));
^
equality constraints: Tuple
lower bounds: Integer
where K,T are type-variables:
K extends Object declared in method <T,K>groupingBy(Function<? super T,? extends K>)
T extends Object declared in method <T,K>groupingBy(Function<? super T,? extends K>)
我当前的代码:
import java.util.stream.IntStream;
import java.util.stream.Collectors;
import java.util.Map;
public class Test{
private static final class Tuple {
private final Integer t1;
private final Integer t2;
private Tuple(final Integer t1, final Integer t2) {
this.t1 = t1;
this.t2 = t2;
}
public Integer getT1() { return t1; }
public Integer getT2() { return t2; }
}
public static void main(String []args){
System.out.println("Hello World");
Map<Tuple, Integer> results =
IntStream.range(1, 10).boxed()
.map(p -> new Tuple(p, p % 2)) // Expensive computation
.filter(p -> p.getT2() != 0)
.collect(Collectors.groupingBy(p -> p.getT2()));
results.forEach((k, v) -> System.out.println(k + "=" + v));
}
}
我本人对 Java 8 还很陌生,解决方案可能有误,但我不知道错误的含义或如何解决它。 Tuple 类过去也是泛型的,但由于我认为这是导致问题的原因,所以我删除了泛型类型,但仍然存在相同的错误。
【问题讨论】: