将Array值与相同的键组合在一起

时间:2013-02-16 12:10:15

标签: java android arrays map hashmap

我有一个包含我所有数据的列表:setData

List<Map<String, Integer>> setData = new ArrayList<Map<String, Integer>>();
Map<String, Integer> set;

并且这样添加了值(这种情况发生在循环中,当它迭代游标时):

set = new HashMap<String, Integer>();
set.put("value", value);
set.put("day", day);
setData.add(set);

数组的排序 ,从'day'的最低值到'day'的最高值。

我的问题:我想将所有“值”与相同的“日期”组合在一起,需要添加或减去“值”,我的最终数组每天只保存一个值

2 个答案:

答案 0 :(得分:1)

试试这个:

 Map<Integer, Integer> dayValue = new HashMap<Integer, Integer>();
 for(Map<String, Integer> set : setData) {
     int day = set.get("day"); 
     int value = set.get("value");
     int storedValue = dayValue.get(day);
     // do your addition or subtraction with value and storedValue,
     // and update the map after that
     dayValue.put(day, storedValue);
 }

因此,对于每一天,您将拥有 a 值。在这种情况下无需使用array,因为您希望为每个unique天保留一个值,hashmap就可以了。

答案 1 :(得分:1)

尝试这种方式,留下不必要的字段:

set = new HashMap<Integer, Integer>(); 

在每个周期中:

if (set.containsKey(day))
{
  value += set.get(day);
} 

set.put(day, value);

通过这种方式,您将获得每天一个值的哈希值。

相关问题