泛型方法mapvalues(map,mapper)的什么签名?

u4dcyp6a  于 2021-07-13  发布在  Java
关注(0)|答案(0)|浏览(164)

我写了一个习惯 CollectionUtils 类来弥补Java8中某些重要功能特性的不足。然而,我并不精通复杂的泛型,我不确定给以下方法什么签名:

  1. public static <K,V,N> Map<K,N> mapValues(Map<K,V> map, Function<V,N> mapper) {
  2. return map.entrySet().stream().collect(Collectors.toMap(Map.Entry::getKey,mapper.compose(Map.Entry::getValue)));
  3. }

它是这样工作的,但不是很好。例如,以下代码不编译:

  1. CollectionUtils.mapValues(
  2. candidates.stream().collect(groupingBy(x -> x.category)),
  3. list -> list.stream().sorted(Comparator.reverseOrder()).collect(Collectors.toList()));

(错误:类别无法解析,或者不是字段 category 是一个 Candidate ,但编译器无法推断 x 在这里设置为 Object ),而这编译得很好:

  1. Map<String,List<Candidate>> map = candidates.stream().collect(groupingBy(x -> x.category));
  2. return CollectionUtils.mapValues(map,list -> list.stream().sorted(Comparator.reverseOrder()).collect(Collectors.toList()));

有什么方法可以帮助编译器成功地推断出Map的类型吗?

暂无答案!

目前还没有任何答案,快来回答吧!

相关问题