gpt4 book ai didi

Java 8 流聚合通用列表以映射

转载 作者:搜寻专家 更新时间:2023-11-01 01:51:09 24 4
gpt4 key购买 nike

我试图通过将它应用到一个小型家庭项目中来让自己使用 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

最佳答案

你不应该使用原始类型。要么完全删除 t 的类型规范:

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

或者完全指定它的类型:

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

关于Java 8 流聚合通用列表以映射,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31204780/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com