java - 如何从java中的Dictionary类一次检索一条记录

标签 java dictionary

我正在字典中插入记录,在检索时我使用如下代码:

System.out.println(newLine + "Items in the dictionary..." + dict + newLine);

它给我的结果是:

Items in the dictionary...{pa=1234567890, abcd=8976543245}

但我想要以不同的方式。我想分别访问每个记录和字段。 我想要这样的结果:

Name     Contact
pa       1234567890
abcd     8976543245

最佳答案

Dictionarykeys获取键的方法,您可以迭代它并获取值

    Enumeration<String> e = dictionary.keys();
    while (e.hasMoreElements()) {
        System.out.println(e.nextElement());
    }

如果是自定义集合,可以自己写Iterator

如果是MapHashTable

您可以使用迭代字典

示例

    for (Entry<String, String> entry : dict.entrySet()) {
        System.out.println(entry.getKey() + " " + entry.getValue());
    }
    for (String key : dict.keySet()) {
        System.out.println(key + " " + dict.get(key));
    }

在Java8中

    dict.forEach((k, v) -> System.out.println(k + " " + v));

Dictionarykeys获取键的方法,您可以迭代它并获取值

编辑

将您的声明更改为

Hashtable<String, String> dict = new Hashtable<String, String>();这样您就可以获得迭代 HashTable 的方法

关于java - 如何从java中的Dictionary类一次检索一条记录,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33273401/

相关文章:

java - 从文件到文件程序的写入

java - 将 InputStream 传递给不同的类并获取 NullPointerException

java - 为什么 JVM 的实际内存占用比我的 Xmx 大这么多?

用于桌面应用程序的 JavaFX-8 GUI : Are there Look & Feels like in Swing?

带有 CSV 元组列表的 python 字典

c# - 具有不同数据类型数组作为值的字典

java - 从一个连续字符串中提取重复属性

Swift - 使用未解析的标识符 'map'

java - 使用 Eventbus 重用事件对象

c# - 从 json 中反序列化 Dictionary<string, MyClass>,可能没有 Newtonsoft.Json?