I have to create HashMapinside another HashMap, as shown below, which can store the value inside the internal HashMapone based on the key of the external one HashMapat runtime
i.e. the required output for the program must be in the format
{ 1 = {11 = "aaa",15 = "bbb"}, 2 = {13 = "ccc", 14 = "ddd"} }
where 1,2 is the key value for the Outer HashMap.
Below is the code provided for it. Is there a better approach to increase productivity.
HashMap<Integer, HashMap<Integer, String>>Outer
= new HashMap<Integer, HashMap<Integer,String>>();
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int count = Integer.parseInt(br.readLine());
for(int i =0;i<count;i++)
{
String input[] = br.readLine().split("\\s");
int key = Integer.parseInt(input[0]);
if(Outer.isEmpty() || !Outer.containsKey(key))
{
HashMap<Integer, String> inner = new HashMap<Integer, String>();
inner.put(Integer.parseInt(input[1]),input[2]);
Outer.put(key, inner);
}
else if(Outer.containsKey(key))
{
HashMap<Integer, String> inner = (HashMap<Integer, String>) Outer.get(key).clone();
inner.put(Integer.parseInt(input[1]), input[2]);
Outer.put(key, inner);
}
}
source
share