I am supposed to created a HashMap inside another HashMap as shown below which can store the value inside the inner HashMap based on the key of the outer HashMap at the runtime
i.e. required output for program should be of the format
{ 1 = {11 = "aaa",15 = "bbb"}, 2 = {13 = "ccc", 14 = "ddd"} }
where 1,2 are Key values for Outer HashMap.
Below is the Code provided for it Is there any better approach to improve performance
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");
//HashMap<Integer,String>inner = new HashMap<Integer, String>();
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);
}
}
Similar to Vadim’s answer, but further improved – as it doesn’t require a call to both
containsKeyas well asget:It also has some minor improvements for naming conventions, and use of the Collections interfaces instead of concrete types.
I also removed the call to
clone. This could be a slight savings – and I don’t think it would have given you your expected results.Finally – one other thing that I changed that could be a slight improvement is using a pre-compiled Pattern for the splitting of your String into fields.