将Java流计数为整数而不是长整数 [英] Count Java Stream to Integer, not Long

查看:60
本文介绍了将Java流计数为整数而不是长整数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要计算一些特殊束的出现.

I need to count occurences of some special bundles.

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

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

This code does not compile because counting returns Long. Is there any beautiful way to return Map<Integer, Integer>?

我有这个主意,但是很丑

I have this idea, but it`s ugly

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

推荐答案

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

You can use Collectors.collectingAndThen to apply a function to the result of your Collector:

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

如果您不仅需要强制转换,还需要其他语义,请使用其他转换代码替换Long::intValue.

If you need some other semantics than just a cast, replace Long::intValue with some other conversion code.

这篇关于将Java流计数为整数而不是长整数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆