2015-05-19 29 views
3

正如Stuart Marks指出的那样,我试图为here指出的问题编写一个解决方案来使用辅助类。我被困在代码由于此错误:推理变量K具有不兼容的边界

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类过去也是通用的,但由于我认为导致了问题,我删除了泛型类型,但仍然存在相同的错误。

+2

参见http://stackoverflow.com/questions/29946938/java-streams-groupingby-same-elements/29947129#29947129(第二部分) –

回答

4

collect()groupingBy()不做你认为他们做的事。你的任务的结果类型,因为它是现在的问题是:

Map<Integer, List<Tuple>> results = ... 

换句话说,你被p.getT2()Integer)分组和各组,收集组的元组为List<Tuple>,导致是这样的:

1=[[email protected], [email protected], [email protected], 
    [email protected], [email protected]] 
+0

谢谢!我愚蠢。我想我太急于为这个问题找到一个解决方案,而不是很好地阅读api :-)。 – Juru

+1

@Juru:嗯,这个API很难阅读......但是如果你使用的是IDE,你可以让它自动为你完成指定的类型 - 这可能有助于:) –

+0

是的好主意,我正在写它在一个在线编译器:-)。那里没有自动完成。 – Juru

相关问题