这是我的密码:
Map<String, Collection<? extends String>> test = listOfTipusIdentificadorPacient.stream()
.collect(Collectors.groupingBy(
TipusIdentificadorPacient::getOid,
Collectors.mapping(TipusIdentificadorPacient::getUse, Collectors.toList())
)
);我收到了这条汇编信息:
类型不匹配:不能从Map转换为Map>
我不太清楚如何覆盖Collectors.mapping以便:
return:
Map<String,Collection<? extends String>>
instead of:
Map<String,List<String>>为了使其编译,我尝试创建另一个通用代码。
守则是:
Stream<Map.Entry<String, String>> streamOfPairedStrings = Stream.of();
Map<String, Collection<? extends String>> test = streamOfPairedStrings
.collect(Collectors.groupingBy(
Map.Entry::getKey,
Collectors.mapping(Pair::getValue, Collectors.toList())
)
);有什么想法吗?
发布于 2021-09-01 07:30:54
因此,编译错误的原因是:
Map<String, List<String>> mapOfLists = Map.of();
Map<String, Collection<? extends String>> mapOfCollections = Map.of();因此,考虑到这一守则是合法的:
mapOfCollections.put("", Set.of());也就是说,您可以在值不是List<String>的地方放置键/值对。因此,您不能分配:
mapOfCollections = mapOfLists;因为这样您就可以执行上面的put,从而导致堆污染。编译器就会阻止你这么做。
// If it were legal...
mapOfCollections = mapOfLists;
mapOfCollections.put("", Set.of());
List<String> list = mapOfLists.get(""); // ClassCastException!我认为您可以在Collectors.collectingAndThen中使用toList()来完成这个任务,其中“然后”是一个不受约束的强制转换:
Collectors.collectingAndThen(Collectors.toList(), a -> a)您不能用Function.identity()完成此操作的原因是collectingAndThen和Function.identity()签名的组合
collectingAndThen(Collector<T,A,R> downstream, Function<R,RR> finisher)意味着函数的输入类型必须与收集器的输出类型匹配--在您的示例中,List<String>.Function.identity()是一个Function<T, T> (没有通配符)。因为函数的输入类型必须是List<String>.,所以它的输出类型也是List<String>。
a -> a看起来像身份函数,但实际上它更通用:它是一个向上转换的函数,Function<? extends T, T>,这意味着输出类型不必与输入完全相同,但它可以安全地转换。
因此,在这里,a -> a充当一个Function<List<String>, Collection<? extends String>> (因为List<String>是Collection<String>的一个子类型,它是Collection<? extends String>的一个子类型)。
https://stackoverflow.com/questions/69009395
复制相似问题