How do I print out all keys in hashmap?

41,949

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"]
Share:
41,949
Gurkang
Author by

Gurkang

Trying to learn some C# programming.

Updated on November 11, 2020

Comments

  • Gurkang
    Gurkang over 3 years

    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));
    }
    }
    
  • Gurkang
    Gurkang over 9 years
    Thank you, I didn't know that.
  • jjlema
    jjlema over 9 years
    If the answer helped you, please mark it as accepted, thank you.