【问题标题】:edit hashmap with hashset as value使用 hashset 作为值编辑 hashmap
【发布时间】:2018-05-21 05:43:43
【问题描述】:

我有以下代码:

HashMap<String, HashSet<Person>> index = new HashMap<String, HashSet<Person>>();
public static void indexDB(String base)
{
    for(Person i: listB)
    {
        if(name.equals(base))
        {

        }
}

listB 是一个包含 Person 元素的数组。

所以,如果一个人的名字与字符串基数匹配,他们就会被附加到索引 HashMap 中的一对键值上。每个键的 HashSet 包含其名称与字符串基数匹配的 Persons。如何才能做到这一点?

另外,我有一个类似的方法:

public void printPersons(String sth)
{

}

我希望它打印每次调用的键的 HashSet 中包含的人员。

谢谢

【问题讨论】:

    标签: java


    【解决方案1】:

    使用putIfAbsent 插入一个空的哈希集占位符。

    然后将新人添加到现有集合中:

    HashMap<String, HashSet<Person>> index = new HashMap<String, HashSet<Person>>();
    public static void indexDB(String base)
    {
        for(Person i: listB)
        {
            if(name.equals(base))
            {
                index.putIfAbsent(base, new HashSet<>());
                index.get(base).add(i)
            }
    }
    

    注意:为了正确添加要设置的人员,您必须为您的 Person 类实现 equals()/hashCode(),因为 Set 使用 equals() 来确定唯一性

    【讨论】:

    • 这里的 putIfAbsent 有什么用? put() 也可以在这里工作
    • 如果你使用 put,下一次迭代会将现有的 set 替换为现有 key 的空 set。 putIfAbsent 等于 if(map.get(key) == null) { map.put(key, value); }
    【解决方案2】:

    不要在每次迭代中创建 HashSet 对象,而是仅在名称匹配时创建它,如下面的代码 -

    public static void indexDB(String base)
    {
        for(Person i: listB)
        {
            if(index.containsKey(base)){
                HashSet<Person> existingHS = index.get(base);
                existingHS.add(i);
                index.put(base,existingHS);
            }else{
                HashSet<Person> hs = new HashSet<Person>();
                hs.add(i);
                index.put(base,hs);
            }
    }
    

    【讨论】:

    • 如果你这样做,集合总是最多包含元素。错了
    【解决方案3】:

    这样做

    HashMap<String, HashSet<Person>> index = new HashMap<String, HashSet<Person>>();
    public static void indexDB(String base)
    {
    HashSet<Person> h = new HashSet<String>();
        for(Person i: listB)
        {
            //I assume it is i.name here
            if(i.name.equals(base))
            {
                h.add(i);
            }
        }
         index.put(base,h);
    }
    

    对于打印,执行此操作

    public void printPersons(String sth)
    {
        Map mp = index.get(sth);
        Iterator it = mp.entrySet().iterator();
        while (it.hasNext()) {
            Map.Entry pair = (Map.Entry)it.next();
            System.out.println(pair.getKey() + " = " + pair.getValue());
        }
    }
    

    【讨论】:

    • 在 h.add() 中你应该放置 person 对象,而不是类名本身 :)
    • @DerickDaniel 哦,是的。对不起^_^
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-03-05
    • 1970-01-01
    • 2021-05-06
    • 2013-04-23
    • 1970-01-01
    相关资源
    最近更新 更多