[英]Populate Map<String, Map<String, Integer>> with values
I need to fill Map<String, Map<String, Integer>>
with values.我需要用值填充Map<String, Map<String, Integer>>
。 My code is as follows:我的代码如下:
// tags, <types, prices>
Map<String, Map<String, String>> outter = new HashMap<>();
List<String> tags = new ArrayList<String>();
tags.add("1tag");
tags.add("2tag");
List<String> types = new ArrayList<String>();
types.add("paper");
types.add("metal");
List<String> prices = new ArrayList<String>();
prices.add("1.20");
prices.add("2.20");
for (int t = 0; t < tags.size(); t++) {
Map<String, String> inner = new HashMap<>();
for (int tp = 0; tp < types.size(); tp++) {
for (int p = 0; p < prices.size(); p++) {
inner.put(types.get(tp), prices.get(p));
}
}
outter.put(tags.get(t), inner);
}
System.out.println("filled outter:" + outter);
The result is:结果是:
filled outter:{2tag={paper=2.20, metal=2.20}, 1tag={paper=2.20, metal=2.20}}
The correct result I want is:我想要的正确结果是:
filled outter:{2tag={paper=1.20, paper=2.20, metal=1.20, metal=2.20}, 1tag={paper=1.20, paper=2.20, metal=1.20, metal=2.20}}
How to prevent overriding values and get correct result?如何防止覆盖值并获得正确的结果? Help..帮助..
As reported by others Java's Map interface maps each key to a single value.正如其他人所报告的那样,Java 的 Map 接口将每个键映射到单个值。 If you want to assign multiple values to a single key, you can either do that manually (mapping to a List).如果您想为单个键分配多个值,您可以手动执行此操作(映射到列表)。 Or use a library that already has that, like Guava's Multimap for your inner map.或者使用已经拥有它的库,例如Guava 的 Multimap用于您的内部 map。
That way you will have something like:这样你就会有类似的东西:
filled outter:{2tag={paper=[1.20, 2.20], metal=[1.20, 2.20]}, 1tag={paper=[1.20, 2.20], metal=[1.20, 2.20]}}
And you would define your map as:您将 map 定义为:
Map<String, Multimap<String, String>> outter = new HashMap<>();
You have an example usage of Multimap here .您有一个 Multimap here的示例用法。
Because you can't set two keys inside a Map with the same name.因为您不能在 Map 中设置两个具有相同名称的键。 You should create a ArrayList or something simular inside the outer Map.您应该在外部 Map 内创建一个 ArrayList 或类似的东西。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.