在 Java 中递归创建 Hasmap
我正在尝试为我作为输入的每个文档创建一个新的 HashMap
。在伪代码中,我可以想到类似的东西:
For(eachInputDoc)
{
Map<String, String> mapInputNumber = new HashMap<String, String>;
}
因此,对于 4 个文档,您将拥有:
mapInput1
mapInput2
mapInput3
mapInput4
我怎样才能完成这个?
I'm trying to create a new HashMap
for each document I have as input. In pseudeocode I can think of something like:
For(eachInputDoc)
{
Map<String, String> mapInputNumber = new HashMap<String, String>;
}
So that for 4 documents you would have:
mapInput1
mapInput2
mapInput3
mapInput4
How can I accomplish this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(7)
我建议你制作一个 HashMap 的 ArrayList。
I suggest you make an ArrayList of HashMaps.
您无法在 Java 中动态生成诸如
mapInput1
、mapInput2
等名称。您需要考虑数组或列表。而且你的问题不是递归的。You cannot dynamically generate names like
mapInput1
,mapInput2
, etc in Java. You need to think of array orList
. Also your problem is not recursive.我会做这样的事情:
然后您可以通过执行以下操作轻松访问每个文档的数据
I'd do something like this:
Then you can easily access the data for each doc by doing
如果您知道/想要引用文档的名称,您甚至可以使用 HashMap 的 HashMap。
If you know/want to reference the name of the document, you could even use a HashMap of HashMaps.
我会有另一个地图来保存mapInputs,如下所示:
您可以使用List(数组,链接)而不是MAP,但这取决于您将如何访问该inputMaps!我想说使用 ArrayList 也是一个不错的选择!
I would have another map to hold the mapInputs something like this:
U have the aproach of having a List(array,linked) instead of MAP, but this depends of how you`re gonna access that inputMaps! I would say that using a ArrayList is a good one too!
您需要将哈希映射放入另一个(动态)容器中,例如 ArrayList 或其他 HashMap。
You need to put your hash maps into another (dynamic) container like ArrayList or other HashMap.
看起来您正在尝试动态声明变量。在 Java 中你不能这样做——变量本身是在编译时确定的。但是,您可以创建一个列表:
It looks like you're trying to declare variables dynamically. You can't do that in Java - the variables themselves are determined at compile time. However, you could create a list: