Java 如何打印出哈希图中的所有键?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/26847081/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-11 03:23:04  来源:igfitidea点击:

How do I print out all keys in hashmap?

javahashmap

提问by Gurkang

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

采纳答案by nafas

Here we go:

开始了:

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

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

这将使用 Set.toString() 方法打印出 Map 中的一组键。例如 :

["a","b"]

回答by jjlema

Maps have a method called KeySet with all the keys.

Maps 有一个名为 KeySet 的方法,其中包含所有键。

 Set<K> keySet();

回答by BullyWiiPlaza

You need to get the keySetfrom your hashMapand iterate it using e.g. a foreachloop. This way you're getting the keyswhich can then be used to get the valuesout of the map.

您需要keySet从您的中获取hashMap并使用例如循环对其进行迭代foreach。通过这种方式,您将获得keys可用于values从地图中取出的 。

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