【发布时间】:2014-09-15 15:07:44
【问题描述】:
我有一个如下格式的对象
Map<String, List<ObjectDTO>> mapOfIndicators = new HashMap<>();
ObjectDTO 是
public class ObjectDTO {
private static final long serialVersionUID = 1L;
private String iName;
private String dName;
private String countryName;
private int year;
//Since the value can be empty, using String instead of Double
private String newIndex;
}
我正在尝试计算 newIndex 值的平均值,因为 getNewIndex 是字符串,所以基本上我无法做到这一点,并且可以有空字符串(值)。我无法将 null 值转换为 0,因为 newIndex 中将有 0 个值。
有没有更简单的方法来计算平均值?
例如。
mapOfIndicators = new HashMap<>();
List<IndicatorTableDTO> _tempValue = new ArrayList();
IndicatorTableDTO _iTDTO = new IndicatorTableDTO("iName", "dName", "countryName1", 2012, "1.00");
_tempValue.add(_iTDTO);
_iTDTO = new IndicatorTableDTO("iName", "dName", "countryName2", 2012, "");
_tempValue.add(_iTDTO);
_iTDTO = new IndicatorTableDTO("iName", "dName", "countryName3", 2012, "0.02");
_tempValue.add(_iTDTO);
_iTDTO = new IndicatorTableDTO("iName", "dName", "countryName4", 2012, "-0.25");
_tempValue.add(_iTDTO);
_iTDTO = new IndicatorTableDTO("iName", "dName", "countryName5", 2012, "0.10");
_tempValue.add(_iTDTO);
mapOfIndicators.put("Test1", _tempValue);
_iTDTO = new IndicatorTableDTO("iName", "dName", "countryName1", 2012, "0.10");
_tempValue.add(_iTDTO);
_iTDTO = new IndicatorTableDTO("iName", "dName", "countryName2", 2012, "", "", "");
_tempValue.add(_iTDTO);
_iTDTO = new IndicatorTableDTO("iName", "dName", "countryName3", 2012, "", "", "");
_tempValue.add(_iTDTO);
_iTDTO = new IndicatorTableDTO("iName", "dName", "countryName4", 2012, "0.25", "", "");
_tempValue.add(_iTDTO);
_iTDTO = new IndicatorTableDTO("iName", "dName", "countryName5", 2012, "1.10", "", "");
_tempValue.add(_iTDTO);
mapOfIndicators.put("Test2", _tempValue);
更新 01:我们可以跳过空字符串/空值;平均值是每个 countryName,所以我想找到相同 contryName 的 newIndex 的平均值,并最终能够得到一个 Map 作为最终结果。
【问题讨论】:
-
您应该包括您的传统计算方式,以使您的意图更加清晰。你想要每个地图条目的平均值还是整个地图的平均值,你想要将空字符串视为 0 还是跳过它们(这不一样……)?
-
有一个简单的方法,只要你定义了平均值应该是多少。如果你不知道字符串为空时整数值应该是什么,我们也不知道。
-
@Holger,更新了底部的问题
-
@JB-Nizet 更新了问题
-
@Vivek:所以
countryName已经是地图的关键了?