Java 8流聚合了要映射的通用列表

时间:2015-07-03 10:39:54

标签: java java-8 java-stream

我试图通过在小型家庭项目中应用Java 8流功能来使用它。最近我在下面转载了这个问题,尽管事实上我明白了问题是什么我找不到修复。我在这里发帖,希望得到一些解释和正确的解决方案。

public class GroupingByStreamTest {
    class Double<A, B> {
        A a;
        B b;

        public Double(A a, B b) {
            this.a = a;
            this.b = b;
        }
    }

    class Triple<A, B, C> extends Double<A, B> {
        C c;

        public Triple(A a, B b, C c) {
            super(a, b);
            this.c = c;
        }
    }

    @Test
    public void shouldGroupToMap() throws Exception {
        List<Triple<String, String, String>> listOfTriples = asList(
            new Triple<>("a-1", "b-1", "c-1"),
            new Triple<>("a-1", "b-2", "c-2"),
            new Triple<>("a-1", "b-3", "c-3"),
            new Triple<>("a-2", "b-4", "c-4"),
            new Triple<>("a-2", "b-5", "c-5"));

        // This code below compiles and executes OK. If I put a   breakpoint
        // in my EDI I can even see the expected Map being created. However
        // if you uncomment the line below and comment the one after it the
        // code will no longer compile. 

        // Map<String, List<Double<String, String>>> myMap =
        Map<Object, List<Double<Object, Object>>> myMap =
        listOfTriples.stream().collect(groupingBy(t -> t.a,
            mapping((Triple t) -> new Double<>(t.b, t.c),toList())));

        assertEquals(2, myMap.size());
    }
}

我得到的编译错误是

Error:(49, 39) java: incompatible types: inference variable A has incompatible bounds
equality constraints: java.lang.String
lower bounds: java.lang.Object

2 个答案:

答案 0 :(得分:4)

您不应该使用原始类型。要删除// method 2: part B // File: MainVC.swift class MainVC : UIViewController, ModalVCDelegate { ... ... func modalVCDismissTapped() { self.dismissViewControllerAnimated(false, completion: nil); } } 的类型规范:

t

或完全指定其类型:

Map<Object, List<Double<Object, Object>>> myMap =
        listOfTriples.stream().collect(groupingBy(t -> t.a,
            mapping(t -> new Double<>(t.b, t.c),toList())));

答案 1 :(得分:3)

您的映射中的原始类型为Triple

如果您调整代码如下:

Map<String, List<Double<String, String>>> myMap =  
listOfTriples
.stream()
.collect(
  groupingBy(t -> t.a, 
    mapping((Triple<String, String, String> t) -> new Double<>(t.b, t.c), toList())
));

它应该有用