0

您将如何将给定地图中的所有值加在一起?

private final Map<String, Double> deviceVoltageMap = new HashMap<String, Double>();

synchronized public double getVoltage(String device) {
    double totalVolts = 0.0;
    for (String key : deviceVoltageMap.keySet()) {
         //?
        }
    return totalVolts;
}
4

3 回答 3

5

Map#values()使用!迭代值

于 2013-11-13T22:36:10.267 回答
2
for (String key : deviceVoltageMap.keySet()) {
        totalVolts += deviceVoltageMap.get(key);
}

Map.get(对象键)

或者:

for(Double value : deviceVoltageMap.values()){
  totalVolts += value;
}

Map.values()

或者:

for(Map.Entry<String, Double> entry : deviceVoltageMap.entrySet()){
   totalVolts += entry.getValue();
}

Map.entrySet()

于 2013-11-13T22:35:48.033 回答
1

请注意,您不需要任何密钥,因此可以简单地迭代Map. 试试这个:

double totalVolts = 0.0;
for (Double val : deviceVoltageMap.values()) {
     totalVolts += val;
}
于 2013-11-13T22:38:12.203 回答