如何用java流对整数列表求和? [英] How to sum a list of integers with java streams?

查看:31
本文介绍了如何用java流对整数列表求和?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想对整数列表求和.它的工作原理如下,但语法感觉不对.代码可以优化吗?

I want to sum a list of Integers. It works as follows, but the syntax does not feel right. Could the code be optimized?

Map<String, Integer> integers;
integers.values().stream().mapToInt(i -> i).sum();

推荐答案

这会起作用,但是 i ->我 正在做一些自动拆箱,这就是它感觉"的原因.奇怪的.mapToInt 将流转换为 IntStream原始整数值元素".以下任一方法都可以使用并更好地解释编译器在使用您的原始语法进行的工作:

This will work, but the i -> i is doing some automatic unboxing which is why it "feels" strange. mapToInt converts the stream to an IntStream "of primitive int-valued elements". Either of the following will work and better explain what the compiler is doing under the hood with your original syntax:

integers.values().stream().mapToInt(i -> i.intValue()).sum();
integers.values().stream().mapToInt(Integer::intValue).sum();

这篇关于如何用java流对整数列表求和?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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