如何将给定地图中的所有值加在一起?
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;
}
答案 0 :(得分:5)
使用Map#values()
!
答案 1 :(得分:2)
for (String key : deviceVoltageMap.keySet()) {
totalVolts += deviceVoltageMap.get(key);
}
可替换地:
for(Double value : deviceVoltageMap.values()){
totalVolts += value;
}
或者替代:
for(Map.Entry<String, Double> entry : deviceVoltageMap.entrySet()){
totalVolts += entry.getValue();
}
答案 2 :(得分:1)
请注意,您不需要任何键,因此可以简单地迭代Map
中的值。试试这个:
double totalVolts = 0.0;
for (Double val : deviceVoltageMap.values()) {
totalVolts += val;
}