devc
devc

Reputation: 43

How to get second key and value from Nested Multimap

I have a complex JsonObject and would like to store the values using a nested Guava multimap because the keys can be duplicated. The problem is how do I access the inner multimap if I have the key to the outer multimap.

This what I have done so far.

Multimap<String, Multimap<String, List<ZoneOrders>>> dictionaryfinal;

Multimap<String, List<ZoneOrders>> dictionaryOrders;

dictionaryfinal = LinkedHashMultimap.create();
dictionaryOrders = LinkedHashMultimap.create();

then I stored my values like below in a loop through the json response:

dictionaryOrders.put(zoneland, zoneorder);                  
dictionaryfinal.put(zonetype, dictionaryOrders);

I am able to get the keyset of the outer multimap easily using

dictionaryfinal.keySet().

After getting one of the keys from the above I want to access the inner multimap linked to the chosen key.

This what I tried so I can have access to the inner multimap:

Multimap<String, List<ZoneOrders>> ordinaryold  = LinkedHashMultimap.create();

ordinaryold = dictionaryfinal.get(item);

But this doesn't work. I get error incompatible types. Not sure what i am doing wrong.

Upvotes: 1

Views: 896

Answers (1)

jbx
jbx

Reputation: 22158

I think that what you want to use is not a Multimap but just a normal Map.

The Multimap<K,V> you are using (presumably the Guava one, because you didn't say), is essentially a Map<K, Set<V>>.

If instead you use a Map your nesting should work:

Map<String, Map<String, List<ZoneOrders>>> dictionaryfinal = new LinkedHashMap<>();

Map<String, List<ZoneOrders>> dictionaryOrders1 = new LinkedHashMap<>();
dictionaryOrders1.put(zoneland, zoneorder);      

dictionaryfinal.put(zonetype1, dictionaryOrders1);

Map<String, List<ZoneOrders>> dictionaryOrders2 = new LinkedHashMap<>();
dictionaryOrders2.put(zoneland2, zoneorder2);      

dictionaryfinal.put(zonetype2, dictionaryOrders2);

Then if you get the items for zonetype1 you can get its nested Map simply by:

 Map<String, List<ZoneOrders>> values1 = dictionaryfinal.get(zonetype1);   

values1 will correspond to the inner multimap of zonetype1 only.

Upvotes: 1

Related Questions