問題描述
我有兩個哈希圖
LinkedHashMap<String, int[]> val1 = new LinkedHashMap<String, int[]>();
LinkedHashMap<String, int> val2 = new LinkedHashMap<String, int>();
每個 hashmap 都有不同的鍵和值.我正在嘗試遍歷兩個哈希圖同時將 val1->int[] 的每個值乘以 val2->int
each hashmap has different key and values. I am trying to iterate over both hashmap
at the same time and multiply each value of val1->int[] to val2->int
最簡單快捷的方法是什么?我在兩個哈希圖中都有數千個值.
What is the easiest and fasted way to do it? I have thousands values in both hashmap.
謝謝
推薦答案
你可能做錯了...
首先,HashMap 不能存儲整數,它需要適當的對象——比如 Integer–數組是一個對象,盡管它隱藏在一些語法糖后面.
First, a HashMap can't store ints, it needs proper objects - like Integer – An array is an object, although it's hidden behind some syntactic sugar.
下面是如何循環遍歷兩張地圖,如果它們碰巧有相同的大小,我想你是這個意思.
Here's how to loop over both maps, if they happens to have the same size, which is what I think you mean.
Iterator<int[]> expenses = val1.values().iterator();
Iterator<Integer> people = val2.values().iterator();
assert val1.size() == val2.size() : " size mismatch";
while (expenses.hasNext()) {
int[] expensesPerMonth = expenses.next();
int persons = people.next();
// do strange calculation
int strangeSum = 0;
for (int idx = 0; idx < expensesPerMonth.length; idx++) {
strangeSum += persons * expensesPerMonth[idx];
}
System.out.println("strange sum :" + strangeSum);
}
但您可能應該回過頭來重新考慮如何存儲數據 –你為什么要使用地圖,關鍵是什么?
But You should probably go back and rethink how you store your data – why are you using maps, and whats the key?
例如,創建一個代表每月支出和人數組合的對象不是更好嗎?
Wouldn't it be better to create an object that represents the combination of monthly expenses and number of people, for instance?
這篇關于javalinkedhashmap迭代的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!