javalinkedhashmap迭代

java linkedhashmap iteration(javalinkedhashmap迭代)
本文介绍了javalinkedhashmap迭代的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着跟版网的小编来一起学习吧!

问题描述

我有两个哈希图

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迭代的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

Show progress during FTP file upload in a java applet(在 Java 小程序中显示 FTP 文件上传期间的进度)
How to copy a file on the FTP server to a directory on the same server in Java?(java - 如何将FTP服务器上的文件复制到Java中同一服务器上的目录?)
FTP zip upload is corrupted sometimes(FTP zip 上传有时会损坏)
Enable logging in Apache Commons Net for FTP protocol(在 Apache Commons Net 中为 FTP 协议启用日志记录)
Checking file existence on FTP server(检查 FTP 服务器上的文件是否存在)
FtpClient storeFile always return False(FtpClient storeFile 总是返回 False)