我試圖通過將它應用於小型家庭項目中來使自己與Java 8流功能一起使用。最近我在下面轉載了這個問題,儘管事實上我明白我找不到解決辦法的問題。我在這裏張貼它希望得到一些解釋和正確的解決方案。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
地圖<字符串,列表<雙>> MYMAP = \t \t //地圖<對象,列表<雙<對象,對象>>> MYMAP = \t \t listOfTriples.stream() \t \t \t \t .collect( \t \t \t \t \t \t Collectors.groupingBy(T - > TA, \t \t \t \t \t \t \t \t Collectors.mapping((三<字符串,字符串,字符串>噸) - >新雙<>(TB,TC), Collectors.toList()))); –
griFlo
您正在''mapping'收藏夾中的lambda中使用原始類型'Triple'參數。嘗試用 'Triple',甚至更簡單,只需使用'mapping(t - > new Double <>(...))',編譯器會推斷它是一個'Triple '爲你。 (你沒有在'groupingBy(t - > ta')中指定它 –
你不應該把類命名爲Double,因爲它與java.lang.Double衝突,這是未來的祕訣問題,將它命名爲'Pair'或者類似的名稱,而'Triple extends Double'則是另一種代碼的味道,一個三元組不是一對,當你嘗試向它添加正確的equals和hashCode方法時,會發現問題 – Holger