问题
I was trying to write a solution for the problem stated here as Stuart Marks pointed out to use a helper class. I got stuck on the code due to this error:
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>)
My current code:
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));
}
}
I'm quite new to Java 8 myself, the solution might be wrong but I have no clue what the error means or how to resolve it. The Tuple class used to be generic as well but since I thought that caused the problem I removed the generic types but the same error remained.
回答1:
collect()
and groupingBy()
do not do what you think they do. The result type of your assignment as it is right now is:
Map<Integer, List<Tuple>> results = ...
In other words, you're grouping by p.getT2()
(Integer
) and in each group, collect the tuples of that group into a List<Tuple>
, resulting in something like:
1=[Test$Tuple@7699a589, Test$Tuple@58372a00, Test$Tuple@4dd8dc3,
Test$Tuple@6d03e736, Test$Tuple@568db2f2]
来源:https://stackoverflow.com/questions/30337231/inference-variable-k-has-incompatible-bounds