問題描述
我應該在另一個 HashMap
中創建一個 HashMap
如下所示,它可以根據鍵將值存儲在內部 HashMap
中運行時外層HashMap
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"} }
其中 1,2 是 Outer HashMap 的鍵值.
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);
}
}
推薦答案
類似于 Vadim 的答案,但進一步改進 - 因為它不需要同時調用 containsKey
和 獲取
:
Similar to Vadim's answer, but further improved - as it doesn't require a call to both containsKey
as well as get
:
Map<Integer, Map<Integer, String>> outer = new HashMap<Integer, Map<Integer, String>>();
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int count = Integer.parseInt(br.readLine());
Pattern splitter = Pattern.compile("\s");
for(int i = 0; i < count; i++){
String input[] = splitter.split(br.readLine());
int key = Integer.parseInt(input[0]);
Map<Integer, String> inner = outer.get(key);
if(inner == null){
inner = new HashMap<Integer, String>();
outer.put(key, inner);
}
inner.put(Integer.parseInt(input[1]), input[2]);
}
它還對命名約定以及使用 Collections 接口而不是具體類型進行了一些小的改進.
It also has some minor improvements for naming conventions, and use of the Collections interfaces instead of concrete types.
我還刪除了對 clone
的調用.這可能會節省一點點 - 我認為它不會給您帶來預期的結果.
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.
這篇關于將 HashMap 存儲在另一個 HashMap 中并提高性能的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!