Output variable K has incompatible bounds
I was trying to write a solution to the problem described here as Stuart Marks pointed out the use of a helper class. I am stuck in 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 completely new to Java 8, the solution might not be right, but I don't know what the error means or how to resolve it. The Tuple class was generic as well, but since I thought this was causing the problem, I removed the generic types, but the same error remained.
source to share
collect()
and groupingBy()
don't do what you think they are doing. The result type of your assignment, as it is now, is:
Map<Integer, List<Tuple>> results = ...
In other words, you are grouping p.getT2()
( Integer
) and, in each group, collect the tuples of that group in List<Tuple>
, which results in something like:
1=[Test$Tuple@7699a589, Test$Tuple@58372a00, Test$Tuple@4dd8dc3,
Test$Tuple@6d03e736, Test$Tuple@568db2f2]
source to share