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.