平均Treemap值,基于Keys

时间:2013-10-02 18:03:06

标签: java map treemap

我有一个树形图,用于存储键和值,如下所示:

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;
         }

我需要一些帮助来弥补一些差距。有一个更好的方法吗?

1 个答案:

答案 0 :(得分:0)

//无法在评论中发布此答案,因为它太大了也会在评论中发布但希望它可以帮助您

public static void main(String [] args){

    //initialize variables
    HashMap<String,ArrayList<Integer>> hm=new HashMap();
    ArrayList<Integer> values=new ArrayList<Integer>();
    values.add(0);
    values.add(1);
    values.add(2);
    hm.put("ko4", values);
    System.out.println(hm.get("ko4").get(0));//prints index 0
    System.out.println(hm.get("ko4").get(1));//prints index 1
    System.out.println(hm.get("ko4").get(2));//prints index 2

}