如何对 Java Hashmap 中的值求和 [英] How to sum values from Java Hashmap

查看:24
本文介绍了如何对 Java Hashmap 中的值求和的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要一些帮助,我正在自学如何在 Java ando 中处理地图,今天我试图从 Hashmap 中获取值的总和,但现在我卡住了.

I need some help, I'm learning by myself how to deal with maps in Java ando today i was trying to get the sum of the values from a Hashmap but now Im stuck.

这是我要求和的地图值.

This are the map values that I want to sum.

HashMap<String, Float> map = new HashMap<String, Float>();

map.put("First Val", (float) 33.0);
map.put("Second Val", (float) 24.0);

作为一个额外的问题,如果我在地图中有 10 或 20 个值怎么办,我如何将所有这些值相加,我需要做一个for"吗?

Ass an additional question, what if I have 10 or 20 values in a map, how can I sum all of them, do I need to make a "for"?

感谢您的帮助.

推荐答案

如果您需要在 Map 中添加所有值,试试这个:

If you need to add all the values in a Map, try this:

float sum = 0.0f;
for (float f : map.values()) {
    sum += f;
}

最后,sum 变量将包含答案.所以是的,为了遍历 Map 的值,最好使用 for 循环.

At the end, the sum variable will contain the answer. So yes, for traversing a Map's values it's best to use a for loop.

这篇关于如何对 Java Hashmap 中的值求和的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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