简体   繁体   中英

Populate Map<String, Map<String, Integer>> with values

I need to fill Map<String, Map<String, Integer>> with values. 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. 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.

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<String, Multimap<String, String>> outter = new HashMap<>();

You have an example usage of Multimap here .

Because you can't set two keys inside a Map with the same name. You should create a ArrayList or something simular inside the outer Map.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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