0

I have 2 maps as shown below and I want the output as a new Map in the required format shown below? Please suggest if this is possible.

Map<String,String> abc = new HashMap<String, String>();
abc.put("Apple", "Mobile");
abc.put("Apple", "Tablet");

Map<String,String> def = new HashMap<String, String>();
def.put("Mobile", "iphone5");
def.put("Tablet", "iMini");

Required o/p format"

Map<String,Map<String,String>> xyz= new HashMap<String, Map<String,String>>();

Example {{Apple={Mobile=[iphone]},Apple={Tablet=[iMini]}}

dazzle
  • 1,346
  • 2
  • 17
  • 29

4 Answers4

1

Simply do as follows:

Map<String,Map<String,String>> xyz = new HashMap<String, Map<String,String>>();
xyz.put("def", def);
xyz.put("abc", abc);

HashMap is a generic class so you can put any object into it.

nkr
  • 3,026
  • 7
  • 31
  • 39
  • This gives me `{def={Apple=Tablet}, abc={Mobile=iphone5, Tablet=iMini}}`. Is it possible to get `{{Apple={Mobile=[iphone]},Apple={Tablet=[iMini]}}`? – dazzle Dec 02 '12 at 18:35
  • @dazzle: No, because you use a `Map`, the keys have to be unique. Maybe you want something like `{"Apple" = {"Tablet" = "iphone", "Mobile" = "iMini"}}`? In that case you have to use a `List` or an array to hold the initial values. – nkr Dec 02 '12 at 18:54
1

Not entirely sure what you are trying to achieve, but it certainly is possible to have map values as other maps as indicated in your 2nd code sample.

But there is a problem with your first sample: when you add the value 'Tablet' with the key 'Apple', it will over-write the value 'Mobile'. A HashMap can only have one value to one key. I don't think there is an implementation of Map which can have multiple values to keys, but it shouldn't be hard to create one.

see HashMap: One Key, multiple Values

Community
  • 1
  • 1
NickJ
  • 9,380
  • 9
  • 51
  • 74
0

Sure, it is possible, you just need to decide what you will use as the key of the outer map:

Map<String,String> abc = new HashMap<String, String>();
abc.put("Apple", "Mobile");
abc.put("Apple", "Tablet");

Map<String,String> def = new HashMap<String, String>();
def.put("Mobile", "iphone5");
def.put("Tablet", "iMini");

Map<String,Map<String,String>> xyz = new HashMap<String, Map<String,String>>();
xyz.put("Foo",abc);
xyz.put("Bar",def);
Jack
  • 131,802
  • 30
  • 241
  • 343
  • sorry for giving an example earlier.. here it is `{{Apple={Mobile=[iphone]},Apple={Tablet=[iMini]}}` – dazzle Dec 02 '12 at 18:31
0

Yes it is possible.

Map<String,Map<String,String>> mapOfMap = new HashMap<String,Map<String,String>>();

mapOfMap.put("map1", new HashMap<String,String>());

mapOfMap.put("map2", new HashMap<String,String>());
Narendra Pathai
  • 41,187
  • 18
  • 82
  • 120