将 Java Stream 计数为整数,而不是长整型

art*_*slv 3 java java-stream collectors

我需要计算一些特殊捆绑包的出现次数。

Map<Integer,Integer> countBundles(){
    return bundles.stream()
        .bla()
        .bla()
        .bla()
        .collect(groupingBy(Bundle::getId), counting()));
}
Run Code Online (Sandbox Code Playgroud)

此代码无法编译,因为计数返回 Long。有什么漂亮的方法返回 Map<Integer, Integer> 吗?

我有这个想法,但是很难看

  map.entrySet().stream()
     .collect(toMap(Map.Entry::getKey, entry -> (int) entry.getValue().longValue()));
Run Code Online (Sandbox Code Playgroud)

Hoo*_*pje 6

您可以使用Collectors.collectingAndThen将函数应用于收集器的结果:

Map<Integer,Integer> countBundles() {
    return bundles.stream()
        .bla()
        .bla()
        .bla()
        .collect(groupingBy(Bundle::getId, collectingAndThen(counting(), Long::intValue)));
}
Run Code Online (Sandbox Code Playgroud)

如果您需要一些其他语义而不仅仅是强制转换,请替换Long::intValue为其他一些转换代码。

  • 为了检测 int 溢出,我建议使用 `Math::toIntExact`。 (2认同)