2016-06-14 63 views
-4

我想在HashMap中containsKey值:的Hashmap包含鍵值

HashMap hm = new HashMap(); 
for (Contact ru : registered_users) { 
    hm.put(ru.getPhone(), ru.getId()); 
} 

if(hm.containsKey(c.getPhone())) { 
    registered_phone_contacts.add(new Contact("", c.getName()); 
               ^^ 
    // Here I need to get value. 
} 

我怎麼能這樣做?

+0

你應該從鍵獲得價值,而不是價值的關鍵。這不是HashMap的工作原理 –

+0

是的。該手機只有一個密鑰。 –

+0

唯一的方法是自己維護一個反向映射(從值到關鍵)。這被稱爲「雙向映射」,並不是JDK中的標準數據結構。 –

回答

0

你可以得到它這樣的:

private String getKey(Integer value){ 
    for(String key : yourHashMap.keySet()){ 
     if(yourHashMap.get(key).equals(value)){ 
      return key; //return the first found 
     } 
    } 
    return null; 
} 

或者在java8流API:

private Optional<String> getKey(Integer value){ 
    return yourHashMap.entrySet().stream().filter(e -> e.getValue().equals(value)).map(e -> e.getKey()).findFirst(); 
} 

它將只能如果有對你的鑰匙唯一值...

更新:

番石榴有BiMap - 檢查出here

0

我假設電話號碼在這裏保證是唯一的,否則爲一個電話號碼獲取相關ID是沒有意義的。如果是這樣,最簡單的解決方案可能只是使用以下方法構建另一個使用反向映射的hashmap:reverseMap.put(ru.getPhone(), ru.getId())。你可以做revserseMap.get(c.getPhone());

從你的例子中,我看不到任何需要正向映射,一旦你有這個逆向映射,所以你可能只是能夠刪除它。

0

不僅僅是Java 8

Map<Long, String> hm = new HashMap<>(); 

final Contact c = ...; 
Optional<Long> idOpt = hm.entrieSet().stream() 
    .filter((e) -> e.getValue().equals(c.getPhone()) 
    .map((e2) -> e2.getKey()) 
    .findAny(); 
idOpt.ifPresent(id -> System.out.println(id)); 
long id = idOpt.orElse(-1L); 
0

您可以檢索除了containsKey方法從地圖的價值:

HashMap hm = new HashMap(); 
for (Contact ru : registered_users) { 
    hm.put(ru.getPhone(), ru.getId()); 
} 

if(hm.containsKey(c.getPhone())) { 
    registered_phone_contacts.add(new Contact(hm.get(c.getPhone()), c.getName()); 
               ^^ 
    // value = hm.get(c.getPhone()) 
} 

或者你可以先檢索的值,改變如果要測試該值而不是包含密鑰:

<TypeOfId> id = hm.get(c.getPhone()); 
if(id != null) { 
    registered_phone_contacts.add(new Contact(id, c.getName()); 

...           ^^ 
} 

希望有幫助, 關注