猿问

带有泛型的 Java 流

我有一个接受 的泛型函数。Collection<? extends T> ts

我也通过了:

Function<? extends T, ? extends K> classifier将每个项目映射到一个键(可能有重复项)TK

Function<? extends T, Integer> evaluator它为项目提供一个整数值。

该函数本身对每个生成都有一个内置的计算(“”)(对于我们的示例,可以像平方一样)int to intInteger

最后,我想对每个键的所有值求和。

所以最终结果是:.Map<K, Integer>

例如,
假设我们有一个列表,我们用它来分类、评估和平方作为内置函数。然后返回的地图将是:["a","a", "bb"]Function.identityString::length{"a": 2, "b": 4}

我该怎么做?(我想最好使用Collectors.groupingBy)


斯蒂芬大帝
浏览 85回答 2
2回答

犯罪嫌疑人X

这是一种方法:public static <T,K> Map<K,Integer> mapper (&nbsp; &nbsp; Collection<T> ts,&nbsp; &nbsp; Function<T, K> classifier,&nbsp; &nbsp; Function<T, Integer> evaluator,&nbsp; &nbsp; Function<Integer,Integer> calculator)&nbsp;{&nbsp; &nbsp; &nbsp;return&nbsp; &nbsp; &nbsp; &nbsp; ts.stream()&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; .collect(Collectors.groupingBy(classifier,&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;Collectors.summingInt(t->evaluator.andThen(calculator).apply(t))));}输出:System.out.println (mapper(Arrays.asList("a","a","bb"),Function.identity(),String::length,i->i*i));是{bb=4, a=2}

德玛西亚99

或者另一种方法:private static <K, T> Map<K, Integer> map(Collection<? extends T> ts,&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; Function<? super T, ? extends K> classifier,&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; Function<? super T, Integer> evaluator,&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; Function<Integer, Integer> andThen) {&nbsp; &nbsp; return ts.stream()&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;.collect(Collectors.groupingBy(&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;classifier,&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;Collectors.mapping(evaluator.andThen(andThen),&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; Collectors.reducing(0, Integer::sum))&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;));}并将其用于:public static void main(String[] args) {&nbsp; &nbsp; System.out.println(map(&nbsp; &nbsp; &nbsp; &nbsp; Arrays.asList("a", "a", "bb"),&nbsp; &nbsp; &nbsp; &nbsp; Function.identity(),&nbsp; &nbsp; &nbsp; &nbsp; String::length,&nbsp; &nbsp; &nbsp; &nbsp; x -> x * x));}
随时随地看视频慕课网APP

相关分类

Java
我要回答