How to sum a list of integers with java streams?(java - 如何将整数列表与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 ->i
正在做一些自动拆箱,这就是它感觉"的原因.奇怪的.mapToInt
将流转换为 IntStream
原始 int 值元素".以下任一方法都可以工作,并使用您的原始语法更好地解释编译器在幕后所做的事情:
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 - 如何将整数列表与java流相加?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:java - 如何将整数列表与java流相加?


基础教程推荐
- 无法使用修饰符“public final"访问 java.util.Ha 2022-01-01
- 减少 JVM 暂停时间 >1 秒使用 UseConcMarkSweepGC 2022-01-01
- “未找到匹配项"使用 matcher 的 group 方法时 2022-01-01
- 降序排序:Java Map 2022-01-01
- Java:带有char数组的println给出乱码 2022-01-01
- 设置 bean 时出现 Nullpointerexception 2022-01-01
- 在 Libgdx 中处理屏幕的正确方法 2022-01-01
- FirebaseListAdapter 不推送聊天应用程序的单个项目 - Firebase-Ui 3.1 2022-01-01
- 如何使用 Java 创建 X509 证书? 2022-01-01
- Java Keytool 导入证书后出错,"keytool error: java.io.FileNotFoundException &拒绝访问" 2022-01-01