How do I list print out all the keys currently stored in my HashMap mapping people to their addresses [closed]

StackOverflow https://stackoverflow.com/questions/20626264

  •  02-09-2022
  •  | 
  •  

Question

How do I list print out all the keys currently stored in my HashMap mapping people to their addresses.

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);
    }
}
}

This is what i've attempted so far and know I need to use the keySet method but am unsure how to apply it.

Was it helpful?

Solution 2

You can use either of the following
1) Use the 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);
    }

or use the Hashmap values method which returns a Collection view of the values contained in the map

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

or directly print the collection returned by values using Arrays

    System.out.println("addressBook.values =" + Arrays.asList(addressBook.values()));

OTHER TIPS

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

or

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

A hashmap has a method keySet which will return a Set of keys

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

In your case

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

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

You need to iterate over all the keys of your phoneBook and get their corresponding address from the addressBook.

for (String key : phoneBook.keySet()) {
   System.out.println("name=" + key + ", address=" + addressBook.get(key));
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top