問(wèn)題描述
我有兩個(gè)哈希圖
LinkedHashMap<String, int[]> val1 = new LinkedHashMap<String, int[]>();
LinkedHashMap<String, int> val2 = new LinkedHashMap<String, int>();
每個(gè) hashmap 都有不同的鍵和值.我正在嘗試遍歷兩個(gè)哈希圖同時(shí)將 val1->int[] 的每個(gè)值乘以 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
最簡(jiǎn)單快捷的方法是什么?我在兩個(gè)哈希圖中都有數(shù)千個(gè)值.
What is the easiest and fasted way to do it? I have thousands values in both hashmap.
謝謝
推薦答案
你可能做錯(cuò)了...
首先,HashMap 不能存儲(chǔ)整數(shù),它需要適當(dāng)?shù)膶?duì)象——比如 Integer–數(shù)組是一個(gè)對(duì)象,盡管它隱藏在一些語(yǔ)法糖后面.
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.
下面是如何循環(huán)遍歷兩張地圖,如果它們碰巧有相同的大小,我想你是這個(gè)意思.
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);
}
但您可能應(yīng)該回過(guò)頭來(lái)重新考慮如何存儲(chǔ)數(shù)據(jù) –你為什么要使用地圖,關(guān)鍵是什么?
But You should probably go back and rethink how you store your data – why are you using maps, and whats the key?
例如,創(chuàng)建一個(gè)代表每月支出和人數(shù)組合的對(duì)象不是更好嗎?
Wouldn't it be better to create an object that represents the combination of monthly expenses and number of people, for instance?
這篇關(guān)于javalinkedhashmap迭代的文章就介紹到這了,希望我們推薦的答案對(duì)大家有所幫助,也希望大家多多支持html5模板網(wǎng)!