【发布时间】:2013-10-02 18:03:06
【问题描述】:
我有一个存储键和值的树状图,如下所示:
key value
ko4 23
ko4 53
ko4 34
po1 100
po1 8
po1 90
po3 99
po3 234
po3 34
我想取每个键的平均值(并最终将它们打印到一个新文件中)。所以我会做平均值并将它们放在另一个地图中,HashMap 用于这个,因为我需要在将它们打印到新文件之前按值排序。新地图如下所示:
Key Value
ko4 36.6
po1 66
po3 122.3
我正在努力让它发挥作用,但我遇到了困难。也许我把事情复杂化了。这是我所拥有的。
Map<String, Integer> map = new TreeMap<String, Integer>();
int sum = 0;
int average;
int number = 1;
map.put(key, value); //I actually read in a file to do this, but so it is reproducible I have it like this, people can put in whatever they please
String lastkey = map.key(0);//I don't know if I can get key somehow
for (int i = 0;i < map.size();i++){ //for the size of the map
thiskey = map.key(i);
if (thiskey.equals(lastkey)){ //if it is the same key as the last one
if (i == 0){
sum = map.get(i);
}else{
sum = sum + map.get(i); //add the values
number++;
}
average = sum / number;
}else{
lastkey = thiskey;
}
我需要一些帮助来弥补这里的一些差距。有一个更好的方法吗?
【问题讨论】:
-
首先,没有
Map——包括TreeMap——同一个键可以有多个值。其次,无法在特定索引处查找键。也许您正在寻找Multimap或Map<String, List<Integer>>。 -
使用 map.keySet() 获取地图中的一组键,但就像@LouisWasserman 所说,地图中不能有相同的键。您需要更改代码以使用不同的数据结构。您可能希望使用 Map 来存储运行平均值,而不是用于初始数据集。
-
Is there a better way to do this?我不这么认为,你的代码看起来不错且可读, -
@Louis Wasserman 我不同意 Map 不能为同一个键有多个值的说法。如果我们有 HashMap
> 会怎样? .这有一个相同键的整数值列表 -
@KaushikSivakumar - 这只是一种键类型(
>)。当他/她将键指定为字符串时,OP 如何有效地从具有该键类型的映射中检索值?