java linkedhashmap迭代 [英] java linkedhashmap iteration
问题描述
我有两个hashmap
I have two hashmap
LinkedHashMap<String, int[]> val1 = new LinkedHashMap<String, int[]>();
LinkedHashMap<String, int> val2 = new LinkedHashMap<String, int>();
每个hashmap具有不同的键和值。我试图同时遍历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
最简单和禁食的方法是什么?我有两个hashmap中的数千个值。
What is the easiest and fasted way to do it? I have thousands values in both hashmap.
谢谢
推荐答案
你可能做错了...
首先,HashMap不能存储int,它需要适当的对象,如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?
这篇关于java linkedhashmap迭代的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!