简体   繁体   English

Java LinkedHashMap迭代

[英]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 我试图同时遍历两个哈希图,并将val1->int[] to val2->int每个值乘以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. 首先,HashMap无法存储整数,它需要适当的对象-如整数-数组是一个对象,尽管它隐藏在某些语法糖的后面。

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. AFAIK,LinkedHashMap具有迭代顺序。 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();
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM