2016-06-14 60 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()); 

...           ^^ 
} 

希望有帮助, 关注