2013-02-16 58 views
1

我有保持我的所有数据的列表:setData结合使用Array值相同的密钥

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

对数组进行排序事后,从“天”为“天”的最高值最低值。

我的问题:我想所有的“价值”与同“日”相结合,“价值”需要增加或减少,我的最后一个数组只持有每天的一个值。

+0

看起来像一个复杂的结构。你有没有考虑使用SQLite? – 2013-02-16 12:16:50

+1

您可以在填充原始结构的同时合并这些值,或者您必须稍后再进行操作?另一方面,如果您要在每个HashMap中存储“值”和“日”值,那么您正在对其进行不当使用。只需使用这两个属性定义一个JavaBeans类。 – thelawnmowerman 2013-02-16 12:17:41

+0

为什么你需要一个哈希列表,当最后一整天都是独一无二的? – Matzi 2013-02-16 12:18:29

回答

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

因此,每一天,你将有一个。在这种情况下不需要使用array,因为您想保留每个unique天的值,hashmap就好。

1

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

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

在每一个周期:

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

set.put(day, value); 

这样,您将有每天一个值的散列。

+0

非常好的想法,但我想它不会在我的情况下工作,因为阵列插入后排序,取决于日值(从低到高)。 – Leandros 2013-02-16 12:45:59

+0

然后使用TreeMap。 – Matzi 2013-02-16 13:50:16