7

I'm trying to learn how hashmaps work and I've been fiddling with a small phonebook program.

But I'm stumped at what to do when I want to print out all the keys.

here's my code:

import java.util.HashMap;
import java.util.*;

public class MapTester
{

private HashMap<String, String> phoneBook;

public MapTester(){
   phoneBook = new HashMap<String, String>();
}

public void enterNumber(String name, String number){
   phoneBook.put(name, number);
}

public void printAll(){
    //This is where I want to print all. I've been trying with iterator and foreach, but I can't get em to work
}

   public void lookUpNumber(String name){
    System.out.println(phoneBook.get(name));
}
}
Bence Kaulics
  • 7,066
  • 7
  • 33
  • 63
Gurkang
  • 155
  • 1
  • 3
  • 16

3 Answers3

13

Here we go:

System.out.println(phoneBook.keySet());

This will printout the set of keys in your Map using Set.toString() method. for example :

["a","b"]
nafas
  • 5,283
  • 3
  • 29
  • 57
1

You need to get the keySet from your hashMap and iterate it using e.g. a foreach loop. This way you're getting the keys which can then be used to get the values out of the map.

import java.util.*;

public class MapTester
{

    private HashMap<String, String> phoneBook;

    public MapTester()
    {
        phoneBook = new HashMap<String, String>();
    }

    public void enterNumber(String name, String number)
    {
        phoneBook.put(name, number);
    }

    public void printAll()
    {
        for (String variableName : phoneBook.keySet())
        {
            String variableKey = variableName;
            String variableValue = phoneBook.get(variableName);

            System.out.println("Name: " + variableKey);
            System.out.println("Number: " + variableValue);
        }
    }

    public void lookUpNumber(String name)
    {
        System.out.println(phoneBook.get(name));
    }

    public static void main(String[] args)
    {
        MapTester tester = new MapTester();

        tester.enterNumber("A name", "A number");
        tester.enterNumber("Another name", "Another number");

        tester.printAll();
    }
}
BullyWiiPlaza
  • 17,329
  • 10
  • 113
  • 185
0

Maps have a method called KeySet with all the keys.

 Set<K> keySet();
jjlema
  • 850
  • 5
  • 8