如何列出打印出当前存储在我的HashMap中的所有键,将人们映射到他们的地址

时间:2013-12-17 05:02:03

标签: java hashmap keyset

如何列出打印出当前存储在HashMap中的所有键,将人们映射到他们的地址。

import java.util.HashMap;

public class MapTester
{
private HashMap<String, String> addressBook = new HashMap<String, String> ();
private String name;
private String address;

public MapTester()
{
    addressBook.put("Zoe", "9 Applebury Street");
    addressBook.put("Mum", "72 Cherry Tree Drive");
    addressBook.put("Dad", "6 Windsor Avenue");        
}    


/**
 * Input the name and address
 */
public void enterContact(String name, String address)
{       
    addressBook.put(name, address);
}

/**
 * Lookup a contact's name from their address.
 */
public String lookupNumber(String name) 
{          
  name = name;  
  return addressBook.get(name);
}  

public void keySet()
{
   for (String contacts : addressBook)
    {
     System.out.println(contacts);
    }
}
}

这是我到目前为止所尝试的,并知道我需要使用keySet方法,但我不确定如何应用它。

4 个答案:

答案 0 :(得分:2)

for (Map.Entry<String, String> entry : addressBook .entrySet()) {
   System.out.println("key=" + entry.getKey() + ", value=" + entry.getValue());
}

Set<String> keys = addressBook.keySet(); // for key set
Iterator iterator=keys.iterator();
while(iterator.hasNext()) {
  System.out.println(iterator.next());
}

答案 1 :(得分:1)

hashmap有一个方法keySet 这将返回一组键

http://docs.oracle.com/javase/7/docs/api/java/util/HashMap.html#keySet()

在你的情况下

Set<String> keys = addressBook.keySet();

 for (String key : keys) {
    System.out.println (key);
 }

答案 2 :(得分:1)

您可以使用以下任一种 1)使用keySet

    Set keys = addressBook.keySet();
    for (Iterator i = keys.iterator(); i.hasNext();) {
        String key = (String) i.next();
        String value = (String) addressBook.get(key);
        System.out.println("key=" + key + ", value=" + value);
    }

或使用Hashmap values方法返回地图中包含的值的Collection视图

    for (String value : addressBook.values()) {
    System.out.println("value=" + value);
    }

或使用values

直接打印Arrays返回的集合
    System.out.println("addressBook.values =" + Arrays.asList(addressBook.values()));

答案 3 :(得分:0)

您需要遍历phoneBook的所有密钥,并从addressBook获取相应的地址。

for (String key : phoneBook.keySet()) {
   System.out.println("name=" + key + ", address=" + addressBook.get(key));
}