How do I print out all keys in hashmap? [duplicate]

陌路散爱 提交于 2019-12-23 12:57:21

问题


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

回答1:


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"]



回答2:


Maps have a method called KeySet with all the keys.

 Set<K> keySet();



回答3:


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


来源:https://stackoverflow.com/questions/26847081/how-do-i-print-out-all-keys-in-hashmap

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!