2013-02-16 33 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