【问题标题】:iterate through all the values of a key in hashtable java遍历哈希表java中键的所有值
【发布时间】:2013-08-18 17:44:34
【问题描述】:
Hashtable<Integer,String> ht = new Hashtable<Integer,String>();
ht.put(1,"student1");
ht.put(1,"student2");

如何遍历“单个键”的所有值?

key:1 values: student1, student2

【问题讨论】:

    标签: java loops hashtable key-value


    【解决方案1】:

    你需要使用:

    Hashtable<Integer, List<String>> ht = new Hashtable<Integer, List<String>>();
    

    并在关联的List 中为特定键添加新的字符串值。

    话虽如此,您应该使用HashMap 而不是Hashtable。后者是遗留类,它早已被前者取代。

    Map<Integer, List<String>> map = new HashMap<Integer, List<String>>();
    

    然后在插入新条目之前,使用Map#containsKey() 方法检查键是否已经存在。如果键已经存在,则获取相应的列表,然后为其添加新值。否则,放置一个新的键值对。

    if (map.containsKey(2)) {
        map.get(2).add("newValue");
    } else {
        map.put(2, new ArrayList<String>(Arrays.asList("newValue")); 
    }
    

    如果可以使用 3rd 方库,另一种选择是使用 Guava's Multimap

    Multimap<Integer, String> myMultimap = ArrayListMultimap.create();
    
    myMultimap.put(1,"student1");
    myMultimap.put(1,"student2");
    
    Collection<String> values = myMultimap.get(1);
    

    【讨论】:

    • 非常感谢。 Arrays.asList("newValue") 是什么意思?
    • @sweet。它使用传递给方法的值创建一个新列表。在Arrays 类中查看该方法的文档。
    【解决方案2】:

    Hashtable 不会为单个键存储多个值。

    当你写 ht.put(1, "student2") 时,它会覆盖 "1" 的值,并且不再可用。

    【讨论】:

    • 谢谢 那我应该使用什么数据结构?
    • Hashtable> ht = new Hashtable>();正如@Rohit Jain 在他的回答中指出的那样。
    【解决方案3】:

    哈希表不允许一个键有多个值。当您向键添加第二个值时,您将替换原始值。

    【讨论】:

      【解决方案4】:

      如果您希望单个键有多个值,请考虑使用 ArrayLists 的 HashTable。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2014-01-21
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-12-08
        • 1970-01-01
        • 2014-06-01
        相关资源
        最近更新 更多