java linkedhashmap iteration
I have two hashmap
LinkedHashMap<String, int[]> val1 = new LinkedHashMap<String, int[]>();
LinkedHashMap<String, int> val2 = new LinkedHashMap<String, 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.
Thanks
You are probably doing it wrong...
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?
AFAIK, a LinkedHashMap has iteration ordering. So, something like this may work:
Iterator myIt1 = val1.entrySet().iterator();
Iterator myIt2 = val2.entrySet().iterator();
while(val1.hasNext() && val2.hasNext()) {
int myarray[] = val1.next();
for(int i = 0; i<myarray.length; i++) {
myarray[i] = myarray[i] * val2.next();
}
}
精彩评论