计算流中的元素并返回long的Integer insted [英] Count Elements in a stream and return Integer insted of long

查看:52
本文介绍了计算流中的元素并返回long的Integer insted的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要计算Stream中的Elements并将其分配给Integer而不进行转换.

I need to count Elements in a Stream and assign it to an Integer without casting.

.count()确实返回long

考虑了.collect(Collectors.reducing(..)),但无法弄清楚. 我觉得有些简单的事情我不明白.

thought about the .collect(Collectors.reducing(..)) but cant figure it out. I feel like there is something simple I don't get.

我的尝试:

Stream<String> s = Stream.of("Hallo ", "Test", "String");
Integer count = s.filter(e -> (e.length() >= lb && e.length() <= ub && !e.contains(" ")))
                 .map(e -> e.toUpperCase())
                 .distinct()
                 .collect(Collectors.reducing(0, e -> 1, Integer::sum)));

System.out.println(count);

推荐答案

简单:不用.

不要投射,也不要使事情变得过于复杂.

Don't cast, but also don't make things overly complicated.

宁愿研究 safe 的方法,以使该int脱离count()返回的long.对于初学者,请参见此处:

Rather look into safe ways of getting that int out of the long returned by count(). See here for starters:

int bar = Math.toIntExact(someLong);

例如.当您100%确定计算值始终适合int时,则只需避免降低可能引发的ArithmeticException的捕获量.而且您仍然有一种感觉,那就是您无法不注意就无法超车".

for example. When you are 100% sure that the computed value always fits within int, then you just avoid putting down the catch for the potentially thrown ArithmeticException. And you still got that good feeling that you can't "overrun" without noticing.

但是如前所述:当您可以使用内置功能对事物进行计数并将其转换为int/Integer时,不要花费时间/精力专门计算自己的东西.请记住:您输入到代码中的每个字符都需要 read 并在以后理解.因此,随着时间的流逝,甚至还有"20个字符"的总和.因此,当您始终倾向于较短的解决方案时,只要它们易于阅读/理解即可.

But as said: don't invest time/energy into specially computing your own stuff, when you can use built-in functionality to count things, and turn them into int/Integer. Remember: each character you put into code needs to be read and understood later on. Thus even "20 characters" more add up over time. So when you always lean towards the shorter solution, as long as they are easy to read/understand.

这篇关于计算流中的元素并返回long的Integer insted的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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