[英]Retrieving the keys of Hashmap
我正在嘗試檢索哈希圖的鍵。
我正在使用哈希映射,如下所示:
HashMap<String, String> inner = new HashMap<String, String>();
HashMap<HashMap<String,String>, String> outer = new HashMap<HashMap<String,String>, String>();
我將值放在兩個哈希圖中,如下所示:
inner.put("1", "one");
inner.put("2", "two");
inner.put("3", "three");
outer.put(inner, "outer1");
outer.put(inner, "outer2");
現在我想獲得輸出
1 one outer1
1 one outer2
2 two outer1
2 two outer2
3 three outer1
3 three outer2
但是我無法做到這一點。 你能幫我解決這個問題嗎?
編輯代碼:
HashMap<String, String> inner = new HashMap<>();
HashMap<String, String> inner1 = new HashMap<>();
HashMap<HashMap<String, String>, String> outer = new HashMap<>();
outer.put(inner, "outer1");
outer.put(inner1, "outer2");
inner1.put("1", "one");
inner1.put("2", "two");
inner1.put("3", "three");
inner1.put("4", "three");
inner.put("1", "one");
inner.put("2", "two");
inner.put("3", "three");
inner.put("4", "three");
outer.forEach((k,v) -> {
k.forEach((k1, v1) -> System.out.println(k1 + " " + v1 + " " + v));
});
正如我在評論中提到的那樣,第二個放置在外部的放置將覆蓋第一個放置(兩者的鍵相同)。 除此之外,一種打印所需內容的方法如下:
outer.forEach((k,v) -> {
k.forEach((k1, v1) -> System.out.println(k1 + " " + v1 + " " + v));
});
只需迭代外部哈希圖,然后再次迭代每個鍵(內部哈希圖)。
希望能幫助到你。
您可以使用這種方式與我一起工作:
for (HashMap<String, String> key : outer.keySet()) {
for (String key2 : key.keySet()) {
System.out.println(key2 + " " + key.get(key2) + " " + outer.get(key));
}
或者這樣:
outer.keySet().stream().forEach((key) -> {
key.keySet().stream().forEach((key2) -> {
System.out.println(key2 + " " + key.get(key2) + " " + outer.get(key));
});
});
但是您無法獲得所需的結果,因為您在HashMap中放置了相同的KEY ,因此HshMap替換了鍵和值。
如果減小HashMap的大小,則只會發現一個而不是兩個:
System.out.println(outer.size());
所以正確的結果
1 one outer2
2 two outer2
3 three outer2
結果錯誤
1 one outer1
1 one outer2
2 two outer1
2 two outer2
3 three outer1
3 three outer2
因此,如果要獲取所需的內容,則應該更改密鑰,例如在第一個HashMap中添加其他內容。
inner.put("1", "one");
inner.put("2", "two");
inner.put("3", "three");
outer.put(inner, "outer1");
inner.put("4","three");
outer.put(inner, "outer2");
希望這可以幫到你。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.